循环

作者: 闲人追风落水 | 来源:发表于2019-07-12 19:32 被阅读0次

1.for


var arr = [];
for(var i = 0; i < arr.length; i++){

}

2.foreach

//1 没有返回值
arr.forEach((item,index,array)=>{
    //执行代码
})
//或者
arr.forEach(function(item,index,array){

})

//参数:value数组中的当前项, index当前项的索引, array原始数组;
//数组中有几项,那么传递进去的匿名回调函数就需要执行几次;

3.map

有返回值,可以return出来,map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);


arr.map(function(value,index,array){
  return XXX
})

var ary = [12,23,24,42,1]; 
var res = ary.map(function (item,index,ary ) { 
    return item*10; 
}) 
console.log(res);//-->[120,230,240,420,10];  原数组拷贝了一份,并进行了修改
console.log(ary);//-->[12,23,24,42,1];  原数组并未发生变化

4.forof遍历

可以正确响应break、continue和return语句


for (var value of myArray) {
    console.log(value);
}

5.filter遍历

不会改变原数组,会返回新的数组


var arr = [
  { id: 1, text: 'aa', done: true },
  { id: 2, text: 'bb', done: false }
]
console.log(arr.filter(item => item.done))
arr.filter(function(item){

})

6.every遍历

every()是对数组中的每一项运行给定函数,如果该函数对每一项返回true,则返回true。

var arr = [ 1, 2, 3, 4, 5, 6 ]; 
console.log( arr.every( function( item, index, array ){ 
        return item > 3; 
})); 

7.some遍历

some()是对数组中每一项运行指定函数,如果该函数对任一项返回true,则返回true。

var arr = [ 1, 2, 3, 4, 5, 6 ]; 

console.log( arr.some( function( item, index, array ){ 
    return item > 3; 
})); 

8.reduce

reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。

var total = [0,1,2,3,4].reduce((a, b)=>a + b); //10
reduce接受一个函数,函数有四个参数,分别是:上一次的值,当前值,当前值的索引,数组

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){
 return previousValue + currentValue;
});

reduce还有第二个参数,我们可以把这个参数作为第一次调用callback时的第一个参数,上面这个例子因为没有第二个参数,所以直接从数组的第二项开始,如果我们给了第二个参数为5,那么结果就是这样的:

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){
 return previousValue + currentValue;
},5);

第一次调用的previousValue的值就用传入的第二个参数代替,

  1. reduceRight
  2. find
  3. findIndex
  4. keys,values,entries

相关文章

网友评论

      本文标题:循环

      本文链接:https://www.haomeiwen.com/subject/tgoykctx.html