常用的(数组or 对象)循环方法总结

数组

1. map ( item,index, arr(原数组) )

   返回一个新的数组,数组中的元素为原始数组调用函数处理后的值,不会改变原始数组。

   可以return

1     let arr = [1,2,3];
2     let tt = arr.map(function(i){
3         console.log(i)
4     return i*2; 
5     })
6     // [2,4,6]

 

2. forEach ( item,index, arr(原数组) )

    循环数组中的每一个元素,对数据的操作会改变原数组

    

1     let arr = [1,2,3]
2     arr.forEach(function(i,index){
3        console.log(i,index)
4     })
5     // 1 0
6     // 2 1
7     // 3 2

 

3. filter(item必须值,index,arr)

   对数组进行过滤,创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

   不会对空数组进行检测,不会改变原始数组

1     let arr = [1,2,3];
2     let tt = arr.filter(function(i){
3        return i>1;
4     })
5     // [2,3]

 

4. some(item, index, arr) , every(item,index,arr)

    some对数组的每一项隐形给定函数,如果该函数对任一项返回true,则返回true (只要有一项符合,就为true),一旦找到符合条件的值,就不会继续迭代下去

  exery对数组中的每一项运行给定函数,如果该函数对每一项返回true,则返回true(如果有一项不符合就为false),一旦有一个不符合条件的值,就不会继续迭代

 

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

console.log( arr.some( function( item, index, array ){ 
    console.log( 'item=' + item + ',index='+index+',array='+array ); 
    return item > 3; 
})); 
// true

console.log( arr.every( function( item, index, array ){ 
    console.log( 'item=' + item + ',index='+index+',array='+array ); 
    return item > 3; 
}));
// false

 

  对象

1.  用 .each() 可以遍历数组和对象

var data = { 
     "a" : 0,
     "b" : 1,
     "c" : 2  
}
$.each(data, (key,Value) => {
     consloe.log( key +","+ data[key] ) 
})
// a, 0
// b, 1
// c, 2

2. 用for in 循环,可以遍历obj

for(key in data){
     console.log(key,data[key])  
}
// a 0
// b 1
// c 2

 

posted @ 2021-08-13 15:08  小黄花呐  阅读(211)  评论(0编辑  收藏  举报