search

Home  >  Q&A  >  body text

javascript - forEach about JS array cannot modify the value of array element

// 第一种(数组forEach无法修改数组元素的值)
let testArr = [1, true, [], '4', {a: 1}];
testArr.forEach((value, index, arr) => {
    value = 6;
    // arr[index] = 6; 此处可以修改成功[6, 6, 6, 6, 6];
});
console.log(testArr); // 输出[1, true, [], '4', {a: 1}]

// 第二种(数组forEach能修改数组元素的属性值)
let objArr = [{a: 1}, {a: 2}, {a: 3}];
objArr.forEach((value, index, arr) => {
    value.a = 6;
});
console.log(objArr); // 输出[{a: 6}, {a: 6}, {a: 6}];

// 第三种(自己实现一个类似forEach的方法)
Array.prototype._forEach = function(callback, _this) {
    if (!_this) _this = this; 
    for (let key in _this) {
        callback.call(_this, _this[key], key, _this);
    }
}
// 调用方法时发现结果一样
// 顺便提问为什么不能写[1,2,3]只能写new Array(1, 2, 3),会报错
let newArr = new Array(1, 2, 3);
newArr._forEach((value, index, arr) => {
    value = 4;
});
console.log(newArr);

希望各位有空帮我解答一下,谢谢~
天蓬老师天蓬老师2746 days ago608

reply all(1)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-24 11:37:57

    Please search: js method parameter passing method. Parameters are passed by value, which means that the basic type copies the value, and the reference type copies the reference and passes it in.

    reply
    0
  • Cancelreply