简体   繁体   English

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

[英]How to loop over an array of arrays using jQuery?

I have an array of arrays. 我有一个数组数组。 I want to be able to loop over each array and for every array I want to add new keys or update existing values. 我希望能够遍历每个数组,并为每个数组添加新键或更新现有值。

Here is what I have 这就是我所拥有的

    var values = [];

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

I want to loop over the values array, and add new keys to the array for each array. 我想循环遍历values数组,并为每个数组向数组添加新键。 (Ie values['123'] and values['456'] ) (即values['123']values['456']

Here is what I tried 这是我试过的

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

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

});

The console shows this error 控制台显示此错误

TypeError: value is undefined

Here is a fiddle 这是一个小提琴

How can I correcly loop over each array item and update the original array? 如何正确循环每个数组项并更新原始数组?

Actually for your case you need to use Object , not Array 实际上,对于您的情况,您需要使用Object ,而不是Array

For constructing non-numeric indexes you should use {} 要构造非数字索引,您应该使用{}

{} - for constructing Object , [] - for constructing Array {} - 用于构造Object[] - 用于构造Array

jQuery.each() can be used to iterate over both objects and arrays . jQuery.each()可用于迭代对象数组

Try this code 试试这个代码

$(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);

        });
    });
});

This is happening because your values array is getting initialized with indexes 123 and 456 . 发生这种情况是因为您的values数组正在使用索引123456初始化。 So, the $.each() function assumes the array length to be 457 and thus starts from element index 0 , though there is no value at that index. 因此, $.each()函数假定数组长度为457 ,因此从元素索引0开始,尽管该索引没有值。

In order to overcome this, you can simply make the following change and it will work- 为了克服这个问题,你可以简单地做出以下改变,它将起作用 -

$.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);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM