如何在JavaScript中填充关联数组的值

3

抱歉我的英语不太好。

我正在使用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
});

出现了错误

类型错误:attribute_sets[i]未定义

也尝试了这个方法

attribute_sets[i]['id'].push($wk_jq(selected).val());

仍然出现相同的错误

请问有人可以指导我如何在这个JS数组中插入值吗? 我希望得到以下输出结果

array
    [0]
      'id':'1',
      'name':'abc'
    [1]
      'id':'2',
      'name':'xyz'

你想获取什么类型的元素? - rrk
我正在尝试从多选中获取id和名称,并将此数组发送到php。 - OBAID
2个回答

2
使用 map() 函数。
attribute_sets = $('.attribute_set :selected').map(function(i, selected){
    return {
       'id' : $(this).val(),
       'name' : $(this).text(),
    }
}).get();

非常感谢,运行得很好... :) 非常感谢 - OBAID

2

尝试

$('.attribute_set :selected').each(function(i, selected){
  attribute_sets.push({
   id: $(selected).val(), // getting id 
   name: $(selected).text() // getting name
});

非常感谢,运行得很好... :) 非常感谢 - OBAID

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接