正在更新$.each中的对象数组

Updating object array in $.each

本文关键字:对象 数组 each 更新      更新时间:2024-01-13

为什么我不能这样做:

var x = [
    { 'z': 3, y: [1,2,3,4]},
    { 'z': 5, y: [2,2,2,2]},
    { 'z': 6, y: [1,4,3,5]},
    { 'z': 8, y: [1,1,3,4]},
];
$(x).each(function() {
    console.log(this.z);
    $(this.y).each(function(i, n) {
       n = n * 2;
    });
});
// expected result from the first iteration would be: 
{ 'z': 3, y: [2,4,6,8]}

我想更新n,但不起作用。可以做到吗?如果可以,如何做到?

执行n = n * 2;时,您只是在更新each处理程序中的局部变量n的值。

$(x).each(function (_, obj) {
    console.log(this.z);
    this.y = $.each(this.y, function (i, n) {
        obj.y[i] = n * 2;
    })
})

演示:Fiddle

试试这个:

$(x).each(function() {
    console.log(this.z);
    var y = this.y;
    $(y).each(function(i, n) {
        y[i] *= 2;
    });
});