js中Array對象提供了一種遍歷數(shù)組的方法,forEach()。
個人覺得還是很好用的,下面給大家做個詳細(xì)的介紹。
forEach() 方法用于調(diào)用數(shù)組的每個元素,并將元素傳遞給回調(diào)函數(shù)。
語法格式為:
array.forEach(function(currentValue, index, arr), thisValue)
currentValue: 表示當(dāng)前元素,個人習(xí)慣用item來表示。
index: 當(dāng)前元素索引號。
arr: 當(dāng)前元素所屬的數(shù)組對象。
舉例說明:
var arr = [123, 232, 31, 313, 3, 13]; // 亂打的
arr.forEach(function (item, index,arr) {
console.log(item);
console.log(index);
console.log(arr);
})

控制臺打印.png
通過控制臺打印的數(shù)據(jù),可以很直觀的理解此方法。
喜歡的朋友請點個贊,謝謝!