如何使用jQuery循环遍历数组?

时间:2016-03-07 23:22:13

标签: javascript jquery arrays

我有一个数组数组。我希望能够遍历每个数组,并为每个数组添加新键或更新现有值。

这就是我所拥有的

    var values = [];

    values['123'] = [];
    values['456'] = [];
    values['123']['x1'] = 'value 1';
    values['123']['x2'] = 'value 2';

我想循环遍历values数组,并为每个数组向数组添加新键。 (即values['123']values['456']

这是我试过的

$.each(values, function(index, value){

  value['x1'] = 'new value 1';
  value['x10'] = 'new value 10';
  value['x20'] = 'new value 20';
  console.log(value);

});

控制台显示此错误

TypeError: value is undefined

这是fiddle

如何正确循环每个数组项并更新原始数组?

2 个答案:

答案 0 :(得分:1)

实际上,对于您的情况,您需要使用Object,而不是Array

要构建非数字索引,您应该使用{}

{} - 用于构建Object[] - 用于构建Array

jQuery.each()可用于迭代对象数组

试试此代码

$(function() {
    $('#x').click(function(e) {
        var values = {}; // here

        values['123'] = {}; // here
        values['456'] = {}; // here
        values['123']['x1'] = 'value1';
        values['123']['x2'] = 'value2';


        $.each(values, function(index, value) {

            value['x1'] = 'new value 1';
            value['x10'] = 'new value 10';
            value['x20'] = 'new value 20';
            console.log(value);

        });
    });
});

答案 1 :(得分:0)

这种情况正在发生,因为您的values数组正在使用索引123456进行初始化。因此,$.each()函数假定数组长度为457,因此从元素索引0开始,尽管该索引没有值。

为了克服这个问题,您只需进行以下更改即可 -

$.each(values, function(index, value){
    if(values[index] !== undefined) { 
        value['x1'] = 'new value 1';
        value['x10'] = 'new value 10';
        value['x20'] = 'new value 20';

        //Update the new values in the values object.
        values[index] = value;
        console.log(value);
    }
});