1. 程式人生 > >js數組遍歷的常用的幾種方法以及差異和性能優化

js數組遍歷的常用的幾種方法以及差異和性能優化

object length 回調 value 鏈式操作 item IT rip 需要

<script type="text/javascript">
            /*對比:
            1、map速度比foreach快
            2、map會返回一個新數組,不對原數組產生影響,foreach不會產生新數組,foreach返回undefined
            3、map因為返回數組所以可以鏈式操作,foreach不能
            4, map裏可以用return ,而foreach裏用return不起作用,foreach不能用break,會直接報錯*/
            /*方法一:*/
            var
arr1 = [1, 2, 3, 4, 5, 6]; for(var i = 0, len = arr1.length; i < len; i++) { //優化性能處理 console.log(arr1[i], ‘for遍歷出來的數據‘); //每個item 1,2,3,4,5,6 } /*方法二:*/ /*forEach方法中的function回調支持3個參數,第1個是遍歷的數組內容;第2個是對應的數組索引,第3個是數組本身*/ var arr2 = [{ name:
‘bob‘, age: 20 }, { name: ‘tom‘, age: 18 }, { name: ‘sos‘, age: 19 } ] arr2.forEach((val, i) => { //
沒有返回值的,對原來數組也沒有影響 console.log(val, ‘遍歷出來的每個obj‘) }); /*方法三:*/ var fruits = [1, 2, 3, 4, 5, 6, 7, 8]; let arr = fruits.map((item, index) => { console.log(item, ‘top‘) console.log(index, ‘top‘) return item * 8 }) console.log(arr, ‘newarr‘) //[8, 16, 24, 32, 40, 48, 56, 64] "newarr" var a = fruits.indexOf("Apple", 4); console.log(a) //for 和 forEach都是普通循環,map 帶返回值並且返回一個新數組; /* *當前元素的值,當期元素的索引值,當期元素屬於的數組對象; 語法:array.map(function(currentValue,index,arr), thisValue) map() 方法返回一個新數組,數組中的元素為原始數組元素調用函數處理後的值。 map() 方法按照原始數組元素順序依次處理元素。 註意: map() 不會對空數組進行檢測。 註意: map() 不會改變原始數組。 * */ /*方法四:*/ /*兼容寫法: 不管是forEach還是map在IE6 - 8 下都不兼容( 不兼容的情況下在Array.prototype上沒有這兩個方法), 那麽需要我們自己封裝一個都兼容的方法:*/ /** * forEach遍歷數組 * @param callback [function] 回調函數; * @param context [object] 上下文; */ Array.prototype.myForEach = function myForEach(callback, context) { context = context || window; if(‘forEach‘ in Array.prototye) { this.forEach(callback, context); return; } //IE6-8下自己編寫回調函數執行的邏輯 for(var i = 0, len = this.length; i < len; i++) { callback && callback.call(context, this[i], i, this); } } /** * map遍歷數組 * @param callback [function] 回調函數; * @param context [object] 上下文; */ Array.prototype.myMap = function myMap(callback, context) { context = context || window; if(‘map‘ in Array.prototye) { return this.map(callback, context); } //IE6-8下自己編寫回調函數執行的邏輯var newAry = []; for(var i = 0, len = this.length; i < len; i++) { if(typeof callback === ‘function‘) { var val = callback.call(context, this[i], i, this); newAry[newAry.length] = val; } } return newAry; } </script>

js數組遍歷的常用的幾種方法以及差異和性能優化