當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JavaScript中的数组循环方法
生活随笔
收集整理的這篇文章主要介紹了
JavaScript中的数组循环方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
var arr=[1,2,3,4,5];
1、遍歷,forEach循環
2、映射,map循環
//如果瀏覽器不支持map if(Array.prototype.map===undefined){Array.prototype.map=function(fun){var newArr=[];//遍歷當前數組中每個元素for(var i=0;i<this.length;i++){//如果當前元素不是undefinedif(this[i]!==undefined){//判斷稀疏數組//調用fun傳入當前元素值,位置i,當前數組,將結果保存在r中//將newArr的i位置賦值為rvar r=fun(this[i],i,this);newArr[i]=r;}}return newArr;} }3、過濾,filter()函數是用來創建一個新的數組,篩選出數組中符合條件的項,組成新數組。
var newArr=arr.filter(function(item, index){ return item >3 }) //[4,5]4、累計,reduce()函數是把數組縮減(reduce)為一個值(比如求和、求積),讓數組中的前項和后項做某種計算,并累計最終值。
var result=arr.reduce(function(prev, next){ return prev + next; }) //15 //如果瀏覽器不支持reduce if(Array.prototype.reduce===undefined){Array.prototype.reduce=function(fun,base){base===undefined && (base=0);for(var i=0; i<this.length; i++){if(this[i]!==undefined){base=fun(base,this[i],i,this);}}return base;} }5、every循環
6、some()函數檢測數組中是否有某些項符合條件
var result=arr.some(function(item, index){ return item>1 }) //只要滿足一個,即為true //如果瀏覽器不支持some if(Array.prototype.some === undefined){Array.prototype.some = function(fun){for(var i=0; i<this.length; i++){if(this[i]!==unefined){var r = fun(this[i],i,this);if(r==true){ return true; }}}return false;} }?
轉載于:https://www.cnblogs.com/camille666/archive/2013/05/12/js_loop_function.html
總結
以上是生活随笔為你收集整理的JavaScript中的数组循环方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SuperSocket 1.5 Docu
- 下一篇: 打开电话Android系统调用