forEach是ECMA5中Array新方法中最基本的一個,就是遍歷,循環。例以下面這個例子:html
[1, 2 ,3, 4].forEach(alert);數組
等同於下面這個for循環瀏覽器
1 var array = [1, 2, 3, 4]; 2 for (var k = 0, length = array.length; k < length; k++) { 3 alert(array[k]); 4 }
Array在ES5新增的方法中,參數都是function類型,默認有傳參,forEach方法中的function回調支持3個參數,第1個是遍歷的數組內容;第2個是對應的數組索引,第3個是數組自己。this
所以,咱們有:spa
[].forEach(function(value, index, array) { // ... });
對比jQuery中的$.each方法:.net
$.each([], function(index, value, array) { // ... });
會發現,第1個和第2個參數正好是相反的,你們要注意了,不要記錯了。後面相似的方法,例如$.map也是如此。prototype
var data=[1,3,4] ; var sum=0 ; data.forEach(function(val,index,arr){ console.log(arr[index]==val); // ==> true sum+=val }) console.log(sum); // ==> 8
mapcode
這裏的map不是「地圖」的意思,而是指「映射」。[].map(); 基本用法跟forEach方法相似:htm
array.map(callback,[ thisObject]);
callback的參數也相似:blog
[].map(function(value, index, array) { // ... });
map方法的做用不難理解,「映射」嘛,也就是原數組被「映射」成對應新數組。下面這個例子是數值項求平方:
var data=[1,3,4] var Squares=data.map(function(val,index,arr){ console.log(arr[index]==val); // ==> true return val*val }) console.log(Squares); // ==> [1, 9, 16]
注意:因爲forEach、map都是ECMA5新增數組的方法,因此ie9如下的瀏覽器還不支持(萬惡的IE啊),不過呢,能夠從Array原型擴展能夠實現以上所有功能,例如forEach方法:
if (typeof Array.prototype.forEach != "function") { Array.prototype.forEach = function() { /* 實現 */ }; }
引用至:http://www.jb51.net/article/81955.htm