【问题标题】:How to populate values in associative array javascript如何在关联数组javascript中填充值
【发布时间】:2016-06-01 13:57:43
【问题描述】:

对不起我的英语不好

我正在使用 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] 未定义

这个也试过

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

仍然出现同样的错误

谁能指导我如何在这个 JS 数组中插入值。 我想要这样的输出

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

【问题讨论】:

  • 你想得到什么类型的元素?
  • 我正在尝试从多选中获取 id 和名称,并且我正在将此数组发送到 php

标签: javascript arrays associative-array


【解决方案1】:

试试

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

【讨论】:

  • 非常感谢你的作品就像一个魅力...... :) 非常感谢
【解决方案2】:

使用map() 函数。

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

【讨论】:

  • 非常感谢你的作品就像一个魅力...... :) 非常感谢
猜你喜欢
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 2011-04-19
  • 2016-04-04
  • 2020-03-31
  • 1970-01-01
相关资源
最近更新 更多