📜  迭代对象 js - Javascript (1)

📅  最后修改于: 2023-12-03 14:57:58.289000             🧑  作者: Mango

迭代对象 js - Javascript

在JavaScript中,迭代对象是指可以被迭代的并且能够返回元素的对象。所谓可迭代对象可以通过for...of循环进行遍历,包括数组、字符串、Map、Set等,而不可迭代对象则需要转换成可迭代对象,例如使用Array.from方法将类数组转换为数组。

可迭代对象
数组

数组是最常用的可迭代对象,可以通过for...of循环遍历数组中的元素。

const arr = [1, 2, 3];
for (const item of arr) {
  console.log(item); // 1, 2, 3
}
字符串

字符串也是一个可迭代对象,可以通过for...of循环遍历字符串中的字符。

const str = 'hello';
for (const ch of str) {
  console.log(ch); // 'h', 'e', 'l', 'l', 'o'
}
Map

Map是ES6中新增的集合类型,它包含了键值对,并且键不允许重复。可以通过for...of循环遍历Map中的键值对。

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (const [key, value] of map) {
  console.log(key, value); // 'a' 1, 'b' 2, 'c' 3
}
Set

Set是ES6中新增的集合类型,它包含了不重复的元素。可以通过for...of循环遍历Set中的元素。

const set = new Set([1, 2, 3]);
for (const item of set) {
  console.log(item); // 1, 2, 3
}
转换为迭代对象

有些数据类型不能直接使用for...of循环进行遍历,需要将它们转换为迭代对象。

字符串转换为迭代对象

字符串可以使用Symbol.iterator方法转换为迭代对象。

const str = 'hello';
const iter = str[Symbol.iterator]();
for (const ch of iter) {
  console.log(ch); // 'h', 'e', 'l', 'l', 'o'
}
类数组转换为迭代对象

类数组可以使用Array.from方法转换为数组,然后再使用for...of循环进行遍历。

const arrLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
const arr = Array.from(arrLike);
for (const item of arr) {
  console.log(item); // 'a', 'b', 'c'
}
总结

在JavaScript中,迭代对象可以是数组、字符串、Map、Set等,可以通过for...of循环进行遍历。对于不能直接使用for...of循环进行遍历的数据类型,需要将它们转换为迭代对象。掌握迭代对象的使用可以让我们更方便地进行数组操作,提高开发效率。