1. 程式人生 > 程式設計 >js陣列forEach例項用法詳解

js陣列forEach例項用法詳解

1、forEach()類似於map(),它還將每個元素依次作用於傳入函式,但不會返回新的陣列。

2、forEach()常用於遍歷陣列,用於呼叫陣列的每一個元素,並將其傳遞給回撥函式。傳輸函式不需要返回值。

例項

var arr=[7,4,6,51,1];
try{arr.forEach((item,index)=>{
      if (item<5) {
       throw new Error("myerr")//建立一個新的error message為myerr
      }
      console.log(item)//只打印7 說明跳出了迴圈
     })}catch(e){
        
console.log(e.message); if (e.message!=="myerr") {//如果不是咱們定義的錯誤扔掉就好啦 throw e } }

知識點擴充套件:

手寫 forEach

forEach()方法對陣列的每個元素執行一次提供的函式

arr.forEach(callback(currentValue [,index [,array]])[,thisArg]);

  • callback

    • currentValue
      陣列中正在處理的當前元素。
    • http://www.cppcns.com
    • index 可選
      陣列中正在處理的當前元素的索引。
    • array 可選
      forEach() 方法正在操作的陣列。
    • thisArg 可選
      可選引數。當執行回撥函式 callback 時,用作 this 的值。
  • 沒有返回值

如果提供了一個 thisArg 引數給 forEach 函式,則引數將會作為回撥函式中的 this 值。否則 this 值為 undefined。回撥函式中 this 的繫結是根據函式被呼叫時通用的 this 繫結規則來決定的。

let arr = [1,2,3,4];

arr.forEach((...item) => console.log(item));

// [1,Array(4)] 當前值

function Counter() {
 this.sum = 0;
 this.count = 0;
}

// 因為 thisArg 引數(this)傳給了 forEach(),每次呼叫時,它都被傳給 callback 函式,作為它的 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)

  • 每個陣列都有這個方法
  • 回撥引數為:每一項、索引、原陣列
Array.prototype.forEach = function(fn,thisArg) {
 var _this;
 if (typeof fn !== "function") {
  throw "引數必須為函式";
 }
 if (arguments.length > 1) {
  _this = thisArg;
 }
 if (!Array.isArray(arr)) {
  throw "只能對陣列使用forEach方法";
 }

 for (let index = 0; index < arr.length; index++) {
  fn.call(_this,arr[index],index,arr);
 }
};

到此這篇關於陣列forEach例項用法詳解的文章就介紹到這了,更多相關js陣列forEach方法的使用內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!