首页 > 技术文章 > es6 遍历总结

fogmisty 2019-02-13 17:47 原文

1、for in / for of

for in --> index是key值

var array = [1,2,3,4,5];
for(let index in array)
{
    console.log(index, array[index]);
};
var obj = {a:1, b:2, c:"qqq"};
for(let index in obj)
{
    console.log(index, obj[index]);
};

 for of --> index是value值

for(let index of array){ 
    console.log(index)
}

比较

注:for of 不支持对象,是直接得到值

obj = {a:1, b:"hello", c: 1.2}

for(let index in obj){console.log(index, obj[index]);};
a 1
b hello
c 1.2

for(let index of obj){console.log(index, obj[index]);};
error

 

for(let index in array){console.log(index, array[index]);};
0 1
1 2
2 3
3 4
4 5

for(let index of array){console.log(index, array[index]);}; 1 2
2 3
3 4
4 5
5 undefined

 

2、forEach

不支持break、return

var array = [1,2,3,4,5];
array.forEach( v => { console.log(v); } );

 

var array = [1,2,3,4,5];
var num = null;
var result = array.forEach( a => 
{
    num += a; return a+1; 
});
> console.log(result);
undefined
> console.log(num)
1 15
> console.log(array)
(5) [1, 2, 3, 4, 5]

 

3、map

映射 return,常用于对象数组获取一个属性等

let a = [1,2,3];
let b = a.map(index => { return index >= 2; });
> console.log(b)
(3) [false, true, true]
> console.log(a)
(3) [1, 2, 3]

 

4、reduce

arr.reduce(callback, [initValue]) 

累加

let nums = [1,2,3,4,5];
let res3 = nums.reduce(function(total,nums){
    return total+nums;
},4);

> console.log(res3);
19 //4+15
let res = [[0,1],[2,3],[4,5]].reduce((a,b)=>{
    return a.concat(b);
},[]);

> console.log(res);
(6) [0, 1, 2, 3, 4, 5]

目标多个属性同时叠加

// 主要对象
var res = [{a:"a", b:1},{a:"b", b:2},{a:"c", b:3}];
// 辅助
var other = {a:0.1, b:0.2, c:0.3}
// 累加计算 --> 累加(b的值*辅助的值) - 10
var out = res.reduce((m,n)=>{return n.b*other[n.a]+m;}, -10);

> console.log(out);
-8.6

求一样的字符数量

var arrString = 'abcdaabc';

arrString.split('').reduce(function(res, cur) {
    res[cur] ? res[cur] ++ : res[cur] = 1;
    console.log(res[cur]+"||"+cur);
    return res;
}, {});
1||a
1||b
1||c
1||d
2||a
3||a
2||b
2||c
{a: 3, b: 2, c: 2, d: 1}

遍历进行操作

[1, 2].reduce(function(res, cur) { 
    res.push(cur + 1); 
    return res; 
}, [])
(2) [2, 3]

 

5、filter

过滤,不会改变原数组

arr.filter(callback, [thisArg])  ([thisArg]可选)

const array = [{id:1, name:'a'},{id:2, name:'b'},{id:3, name:'c'}];
let obj2 = array.filter(obj => obj.id > 1);
> console.log(obj2);
(2) [{…}, {…}]
0: {id: 2, name: "b"}
1: {id: 3, name: "c"}
length: 2
__proto__: Array(0)

 

6、find

找到符合条件的第一个

let a = [1,2,3,4,5];
a.find(n => n < 3);
1
a.find(n => n < 4);
1
a.find(n => n >= 4);
4

 

7、some

有一个满足则为true

var passed = [2, 5, 8, 1, 4].some(v => v>10);
false
passed = [2, 5, 8, 11, 4].some(v => v>10);
true

 

8、every

都满足则为true

passed = [2, 5, 8, 11, 4].every(v => v>10);
false
passed = [2, 5, 8, 11, 4].every(v => v>1);
true

 

9、indexOf / lastindexOf

寻找第一个完全一样的字符出现的位置(正向/反向)
arr.lastIndexOf(searchElement, [fromIndex]);
返回索引或-1

推荐阅读