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. node.js - vue2 的npm run dev 卡死... 网页无法打开. 8080端口没有被占用...2. node.js - vue-cll+sass 样式不出来 已经npm install sass、 sass-loader了3. 微信无法扫描phpqrcode生成的二维码4. javascript - 百度echarts图表如何修改5. index.php错误,求指点6. vim - docker中新的ubuntu12.04镜像,运行vi提示,找不到命名.7. 用PHP怎么在微信公众号里使用模板信息,公众号还未做开发?8. python2.7 - django 无法连接redis9. sqlserver - mysql如何查询多列重复的数据个数?10. python - 在ubuntu下安装scrapy过程遇到的问题
