作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个数组数组。我希望能够遍历每个数组,并为每个数组添加新键或更新现有值。
这是我的
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/
我是一名优秀的程序员,十分优秀!