您的位置:首页 > Web前端 > JavaScript

JavaScript中的数组循环方法

2013-05-12 22:34 621 查看
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++){
//如果当前元素不是undefined
if(this[i]!==undefined){//判断稀疏数组
//调用fun传入当前元素值,位置i,当前数组,将结果保存在r中
//将newArr的i位置赋值为r
var 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: