javascript - 关于JS数组的forEach无法修改数组元素的值
问题描述
// 第一种(数组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方法参数传递方式。参数是按值传递的,也就是说基本类型是拷贝了一份值,引用类型是吧引用拷贝下来传递进去。
相关文章:
1. javascript - 读js权威指南“作为值得函数”产生了疑惑,求释疑2. python中merge后文件莫名变得非常大3. file - Python如何读文件内容修改后写回原文件4. javascript - 为什么 process.stdin 会有 write 方法◔ ‸◔?5. boostrap怎么在移动端不显示sidebar?6. android - 使用listview加载不同item,数据填充错误。7. python3.x - python中的虚拟环境怎样设置一直处于激活状态8. 请问带渐变背景的进度条如何实现?求给点思路9. javascript - 关于js原生事件的绑定与解除绑定10. mysql - 数据库建字段,默认值空和empty string有什么区别 110