一,for of用法(适用iterable类型的集合即Array,Set,Map)

var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for (var x of a) { // 遍历Array
  console.log(x);
}
for (var x of s) { // 遍历Set
  console.log(x);
}
for (var x of m) { // 遍历Map
  console.log(x[0] + '=' + x[1]);
}

//数组运行结果
 A
 B
 C

//set结构运行结果
 A
 B
 C

//Map结构运行结果

1=x

2=y

3=z

二,使用for in

for in遍历对象输出的是键,这也是数组,Map,Set推荐使用for of的原因

2.1 遍历对象:

常用的遍历数组,Map,Set的方法

2.2 遍历数组:

常用的遍历数组,Map,Set的方法

 

 三,forEach(Map,Set,Array适用)

a.forEach(function (element, index, array) {
// element: 指向当前元素的值
// index: 指向当前索引
// array: 指向Array对象本身
console.log(element + ', index = ' + index);
});

 

相关文章:

  • 2022-12-23
  • 2021-07-27
  • 2021-05-31
  • 2022-03-06
  • 2021-12-05
  • 2022-12-23
  • 2021-09-07
猜你喜欢
  • 2022-12-23
  • 2021-08-26
  • 2022-02-07
  • 2021-08-12
  • 2022-12-23
  • 2021-12-24
相关资源
相似解决方案