admin管理员组文章数量:1387380
Can you please help with my problem
I have the following JavaScript object:
var data = {
'rows[0][name]': 'foshka',
'rows[0][tel]': '096',
'rows[0][opt]': 'none'
};
The problem is that i get an error while trying to pass variable as rows index:
var i = 0;
var data = {
'rows['+ i +'][name]': 'one',
'rows['+ i +'][tel]': '096',
'rows['+ i +'][opt]': 'none'
};
Thanks in advance
Can you please help with my problem
I have the following JavaScript object:
var data = {
'rows[0][name]': 'foshka',
'rows[0][tel]': '096',
'rows[0][opt]': 'none'
};
The problem is that i get an error while trying to pass variable as rows index:
var i = 0;
var data = {
'rows['+ i +'][name]': 'one',
'rows['+ i +'][tel]': '096',
'rows['+ i +'][opt]': 'none'
};
Thanks in advance
Share Improve this question edited Jul 22, 2010 at 13:54 Mutation Person 30.5k18 gold badges100 silver badges165 bronze badges asked Jul 22, 2010 at 13:16 alegaalega 211 silver badge2 bronze badges 4- Why are the property names all strings? – Oded Commented Jul 22, 2010 at 13:18
- 2 It is legal syntax, though I have a feeling he is not doing what he thinks he is doing. – MooGoo Commented Jul 22, 2010 at 13:19
- What error are you getting? Is it actually an error, or is data not turning out like you expected? – A. Levy Commented Jul 22, 2010 at 13:21
- See also: stackoverflow./questions/2274242/… – Andy E Commented Jul 22, 2010 at 13:28
2 Answers
Reset to default 4Your code has to be
var data = {};
data[ 'rows['+ i +'][name]' ] = 'one';
data[ 'rows['+ i +'][tel]' ] = '069';
However you might want to change your structure to sth like this:
var data ={};
var i = 0;
data['rows'][i]['name'] = 'one';
Or even cleaner:
var data = { rows[] };
var i = 0;
data['rows'][i] = { 'name' : 'one', 'tel' : 069' };
// so you can access them like this:
alert ( data['rows'][i]['name'] );
I think your data should look like this:
var data = {
rows: [{
name: 'one',
tel: '096',
opt: null
}]
};
That way you can simply add new rows if needed.
本文标签: pass variable into javascript objectStack Overflow
版权声明:本文标题:pass variable into javascript object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744493653a2608888.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论