数组遍历
名称 | 举例 | 运行结果 |
使用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; }); | |
reduceRight | reduceRight() 方法的功能和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