ES6 - 陣列方法 forEach()



forEach() 方法為陣列中的每個元素呼叫一個函式。

語法

array.forEach(callback[, thisObject]);  

引數

  • callback − 用於測試每個元素的函式。

  • thisObject − 在執行回撥時用作 this 的物件。

返回值

返回建立的陣列。

示例:forEach()

var nums = new Array(12,13,14,15)  
console.log("Printing original array......")  

nums.forEach(function(val,index) { 
   console.log(val) 
})  
nums.reverse()  //reverses the array element 
console.log("Printing Reversed array....")  

nums.forEach(function(val,index){ 
   console.log(val) 
})  

輸出

Printing Original Array…. 
12 
13 
14 
15 
Printing Reversed array… 
15 
14 
13 
1
廣告

© . All rights reserved.