如何在关联数组 javascript 中填充值
How to populate values in associative array javascript
抱歉我的英语不好
我在 javascript 工作,我已经构建了一个数组,我想在这个数组中输入值。
var attribute_sets = [];
$('.attribute_set :selected').each(function(i, selected){
attribute_sets[i]['id'] = $(selected).val(); // getting id
attribute_sets[i]['name'] = $(selected).text(); // getting name
});
它给我错误
TypeError: attribute_sets[i] is undefined
也试过这个
attribute_sets[i]['id'].push($wk_jq(selected).val());
仍然出现同样的错误
谁能指导我如何在此 JS 数组中插入值。
我想要这样的输出
array
[0]
'id':'1',
'name':'abc'
[1]
'id':'2',
'name':'xyz'
使用map()
函数。
attribute_sets = $('.attribute_set :selected').map(function(i, selected){
return {
'id' : $(this).val(),
'name' : $(this).text(),
}
}).get();
尝试
$('.attribute_set :selected').each(function(i, selected){
attribute_sets.push({
id: $(selected).val(), // getting id
name: $(selected).text() // getting name
});
抱歉我的英语不好
我在 javascript 工作,我已经构建了一个数组,我想在这个数组中输入值。
var attribute_sets = [];
$('.attribute_set :selected').each(function(i, selected){
attribute_sets[i]['id'] = $(selected).val(); // getting id
attribute_sets[i]['name'] = $(selected).text(); // getting name
});
它给我错误
TypeError: attribute_sets[i] is undefined
也试过这个
attribute_sets[i]['id'].push($wk_jq(selected).val());
仍然出现同样的错误
谁能指导我如何在此 JS 数组中插入值。 我想要这样的输出
array
[0]
'id':'1',
'name':'abc'
[1]
'id':'2',
'name':'xyz'
使用map()
函数。
attribute_sets = $('.attribute_set :selected').map(function(i, selected){
return {
'id' : $(this).val(),
'name' : $(this).text(),
}
}).get();
尝试
$('.attribute_set :selected').each(function(i, selected){
attribute_sets.push({
id: $(selected).val(), // getting id
name: $(selected).text() // getting name
});