js數(shù)組forEach實例用法詳解
1、forEach()類似于map(),它還將每個元素依次作用于傳入函數(shù),但不會返回新的數(shù)組。
2、forEach()常用于遍歷數(shù)組,用于調用數(shù)組的每一個元素,并將其傳遞給回調函數(shù)。傳輸函數(shù)不需要返回值。
實例
var arr=[7,4,6,51,1]; try{arr.forEach((item,index)=>{ if (item<5) { throw new Error("myerr")//創(chuàng)建一個新的error message為myerr } console.log(item)//只打印7 說明跳出了循環(huán) })}catch(e){ console.log(e.message); if (e.message!=="myerr") {//如果不是咱們定義的錯誤扔掉就好啦 throw e } }
知識點擴展:
手寫 forEach
forEach()
方法對數(shù)組的每個元素執(zhí)行一次提供的函數(shù)
arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
-
callback
- currentValue
數(shù)組中正在處理的當前元素。 - index 可選
數(shù)組中正在處理的當前元素的索引。 - array 可選
forEach() 方法正在操作的數(shù)組。 - thisArg 可選
可選參數(shù)。當執(zhí)行回調函數(shù) callback 時,用作 this 的值。
- currentValue
- 沒有返回值
如果提供了一個 thisArg 參數(shù)給 forEach
函數(shù),則參數(shù)將會作為回調函數(shù)中的 this
值。否則 this
值為 undefined?;卣{函數(shù)中 this
的綁定是根據(jù)函數(shù)被調用時通用的 this
綁定規(guī)則來決定的。
let arr = [1, 2, 3, 4]; arr.forEach((...item) => console.log(item)); // [1, 0, Array(4)] 當前值
function Counter() { this.sum = 0; this.count = 0; } // 因為 thisArg 參數(shù)(this)傳給了 forEach(),每次調用時,它都被傳給 callback 函數(shù),作為它的 this 值。 Counter.prototype.add = function(array) { array.forEach(function(entry) { this.sum += entry; ++this.count; }, this); // ^---- Note }; const obj = new Counter(); obj.add([2, 5, 9]); obj.count; // 3 === (1 + 1 + 1) obj.sum; // 16 === (2 + 5 + 9)
- 每個數(shù)組都有這個方法
- 回調參數(shù)為:每一項、索引、原數(shù)組
Array.prototype.forEach = function(fn, thisArg) { var _this; if (typeof fn !== "function") { throw "參數(shù)必須為函數(shù)"; } if (arguments.length > 1) { _this = thisArg; } if (!Array.isArray(arr)) { throw "只能對數(shù)組使用forEach方法"; } for (let index = 0; index < arr.length; index++) { fn.call(_this, arr[index], index, arr); } };
到此這篇關于js數(shù)組forEach實例用法詳解的文章就介紹到這了,更多相關js數(shù)組forEach方法的使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Angularjs結合Bootstrap制作的一個TODO List
這篇文章主要介紹了Angularjs結合Bootstrap制作的一個TODO List 的相關資料,感興趣的小伙伴們可以參考一下2016-08-08淺談JavaScript 函數(shù)參數(shù)傳遞到底是值傳遞還是引用傳遞
下面小編就為大家?guī)硪黄獪\談JavaScript 函數(shù)參數(shù)傳遞到底是值傳遞還是引用傳遞。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08js實現(xiàn)首屏延遲加載實現(xiàn)方法 js實現(xiàn)多屏單張圖片延遲加載效果
這篇文章主要介紹了js實現(xiàn)首屏延遲加載實現(xiàn)方法,以及js實現(xiàn)多屏單張圖片延遲加載效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07