我有一个数组。我希望能够循环每个数组,对于每个数组,我希望添加新的键或更新现有的值。
这是我有的东西
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这是一个小提琴
如何正确循环每个数组项并更新原始数组?
发布于 2016-03-07 23:26:31
实际上,对于您的情况,需要使用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);
});
});
});发布于 2016-03-07 23:35:42
之所以发生这种情况,是因为您的values数组正在使用索引123和456进行初始化。因此,$.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);
}
});https://stackoverflow.com/questions/35856123
复制相似问题