js 循环遍历

1  map

返回一个新的数组,每个元素为调用func的结果, 不改变原数组

let list = [1, 2, 3, 4, 5];

let other = list.map((d, index) => { return d * 2; });

2  filter

返回一个新的数组,每个元素为调用func的结果, 不改变原数组

let list = [1, 2, 3, 4, 5];

let other = list.filter((d, i) => { return d % 2; });

3  foreach

没有返回值,只针对每个元素调用func, 不改变原数组
缺点:无法使用break,return等终止循环。
let list = [1, 2, 3, 4, 5];
let other = [];
list.forEach((d, i) => {
    other.push(d * 2);
});

4  for in

for in也可以循环数组,但是不推荐这样使用,for–in是用来循环带有字符串key的对象的方法。
缺点:只能获得对象的键名,不能直接获取键值。

5  for of 

对于普通的对象,for...in循环可以遍历键名,for...of循环会报错。

for of为ES6提供,具有iterator接口,就可以用for of循环遍历它的成员。也就是说,for of循环内部调用的是数据结构的Symbol.iterator方法。
for of循环可以使用的范围包括数组、Set和Map结构、某些类似数组的对象(比如arguments对象、DOM NodeList对象)、后文的Generator对象,以及字符串。
有些数据结构是在现有数据结构的基础上,计算生成的。
可以遍历 字符串 数组 对象
 
原文地址:https://www.cnblogs.com/xmlily/p/7008586.html