js-数组遍历

数组遍历 

名称举例运行结果
使用forEach遍历
var arr=[1,2,3,4];
arr.forEach(function(val, index) {
console.log(val, index);
});

1 0

2 1

3 2

4 3

使用for..in..遍历
var arr=[1,2,3,4];
for (var i in arr){
   console.log(i,":",arr[i]);

}

0 1

1 2

2 3

3 4

使用for-of遍历
var arr=[1,2,3,4];
for (var value of arr){
  console.log(value);
}

1

2

3

4

.map循环

var ary = [12,23,24,42,1]; 

var res = ary.map(function (item,index,ary ) { 

    return item*10; 

}) 

 

[120,

230,

240,

420,

10];

filter遍历

var arr = [73,84,56, 22,100]

var newArr = arr.filter(item => item>80)

[84,

100]

every遍历

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

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

console.log( arr.every( function( item, index, array ){ 

        return item > 3; 

    })); 

 

false
some遍历

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

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

console.log(

  arr.some( 

    function( item, index, array ){ 

       return item > 3; 

    })); 

true
reduce

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

//reduce接受一个函数,函数有四个参数,分别是:上一次的值,当前值,当前值的索引,数组

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

 return previousValue + currentValue;

});

 
reduceRightreduceRight()方法的功能和reduce()功能是一样的,不同的是reduceRight()从数组的末尾向前将数组中的数组项做累加。 
find  
findIndex  
keys

for (let index of ['a''b'].keys()) {

console.log(index);

}

// 0

// 1

values

for (let elem of ['a''b'].values()) {

console.log(elem);

}

// 'a'

// 'b'

entries

for (let [index, elem] of ['a''b'].entries()) {

console.log(index, elem);

}

// 0 "a"

// 1 "b"

对象遍历 

名称举例结果
Object.keys()
var obj = {'0':'a','1':'b','2':'c'};
Object.keys(obj).forEach(function(key){
     console.log(key,obj[key]);
});

0 a

1 b

2 c

for..in.
var obj = {'0':'a','1':'b','2':'c'};
for(var i in obj) {
    console.log(i,":",obj[i]);
}

0:a

1:b

2:c

使用Object.
getOwnPropertyNames(obj)遍历
var obj = {'0':'a','1':'b','2':'c'};
Object.getOwnPropertyNames(obj)
.forEach(function(key){
    console.log(key,obj[key]);
});

0 a

1 b

2 c

使用
Reflect.ownKeys(obj)
遍历
var obj = {'0':'a','1':'b','2':'c'};
Reflect.ownKeys(obj).forEach(function(key){
    console.log(key,obj[key]);
});

0 a

1 b

2 c

https://blog.csdn.net/guanguan0_0/article/details/87629044

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值