ES6已經到了非學不可的地步了,對於ES5都不太熟的我決定是時候學習ES5了。數組
數組循環變量,最早想到的就是 for(var i=0;i<count;i++)這樣的方式了。函數
除此以外,也可使用較簡便的forEach 方式學習
使用以下:this
function logArrayElements(element, index, array) { console.log('a[' + index + '] = ' + element); } // Notice that index 2 is skipped since there is no item at // that position in the array. [2, 5, , 9].forEach(logArrayElements); // logs: // a[0] = 2 // a[1] = 5 // a[3] = 9
(1)既然IE的Array 沒喲forEach方法, 咱們就給它手動添加這個原型方法。spa
//Array.forEach implementation for IE support.. //https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function(callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; // Hack to convert O.length to a UInt32 if ({}.toString.call(callback) != "[object Function]") { throw new TypeError(callback + " is not a function"); } if (thisArg) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; }
詳細介紹能夠參照:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEachprototype
(2)相似underscore的庫code
underscore的用法blog
_.each([1, 2, 3], function(e){ alert(e); }); => alerts each number in turn... _.each({one: 1, two: 2, three: 3}, function(e){ alert(e) }); => alerts each number value in turn...
Js 此種情況的forEach 不能使用continue, break; 可使用以下兩種方式:
1. if 語句控制
2. return . (return true, false)
return --> 相似continue three
arryAll.forEach(function(e){ if(e%2==0) { arrySpecial.push(e); return; } if(e%3==0) { arrySpecial.push(e); return; } })