javascript - 關(guān)于JS數(shù)組的forEach無法修改數(shù)組元素的值
問題描述
// 第一種(數(shù)組forEach無法修改數(shù)組元素的值)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}]// 第二種(數(shù)組forEach能修改數(shù)組元素的屬性值)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}];// 第三種(自己實(shí)現(xiàn)一個(gè)類似forEach的方法)Array.prototype._forEach = function(callback, _this) { if (!_this) _this = this; for (let key in _this) {callback.call(_this, _this[key], key, _this); }}// 調(diào)用方法時(shí)發(fā)現(xiàn)結(jié)果一樣// 順便提問為什么不能寫[1,2,3]只能寫new Array(1, 2, 3),會(huì)報(bào)錯(cuò)let newArr = new Array(1, 2, 3);newArr._forEach((value, index, arr) => { value = 4;});console.log(newArr);希望各位有空幫我解答一下,謝謝~
問題解答
回答1:請(qǐng)搜索:js方法參數(shù)傳遞方式。參數(shù)是按值傳遞的,也就是說基本類型是拷貝了一份值,引用類型是吧引用拷貝下來傳遞進(jìn)去。
相關(guān)文章:
1. html - vue項(xiàng)目中用到了elementUI問題2. 對(duì)mysql某個(gè)字段監(jiān)控的功能3. javascript - windows下如何使用babel,遇到了困惑4. javascript - js中向下取整5. JavaScript事件6. showpassword里的this 是什么意思?代表哪個(gè)元素7. java - input file類型上傳了一個(gè)文件,想計(jì)算一下上傳文件的大小?8. java - Spring MVC怎么實(shí)現(xiàn)提交表單后跳轉(zhuǎn)?9. python - 為什么正常輸出中文沒有亂碼,zip函數(shù)之后出現(xiàn)中文編程unicode編碼的問題,我是遍歷輸出的啊。10. javascript - table列過多,有什么插件可以提供列排序和選擇顯示列的功能
