您的位置:首页技术文章
文章详情页

javascript - 关于JS数组的forEach无法修改数组元素的值

【字号: 日期:2022-12-08 11:33:39浏览:54作者:猪猪

问题描述

// 第一种(数组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);希望各位有空帮我解答一下,谢谢~

问题解答

回答1:

请搜索:js方法参数传递方式。参数是按值传递的,也就是说基本类型是拷贝了一份值,引用类型是吧引用拷贝下来传递进去。

标签: JavaScript
相关文章: