gpt4 book ai didi

javascript - 如何使用 jQuery 遍历数组数组?

转载 作者:行者123 更新时间:2023-11-29 15:29:47 39 4
gpt4 key购买 nike

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

这是我的

    var values = [];

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

我想遍历值数组,并为每个数组添加新键到数组。 (即 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

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

最佳答案

实际上对于您的情况,您需要使用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);

});
});
});

关于javascript - 如何使用 jQuery 遍历数组数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35856123/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com