循环遍历是写程序很频繁的操作,JavaScript 提供了很多方法来实现。
这篇文章将分别总结数组和对象的遍历方法,新手可以通过本文串联起学过的知识。
数组遍历
方法一:for 循环
for 循环是使用最多,也是性能优化最好的一种遍历方式。
var arr = ["a", "b", "c"];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i])
}
// a b c
同样常规的循环类型还有 while 循环和 do/while 循环。
它们之间的区别在于,for 循环预先知道循环次数,while 循环不知道循环次数,do/while 至少会循环次数。
方法二:for-of 遍历
for-of 是 ES6 新增的语法。它直接遍历值,而不是数组下标(或对象属性)。
var arr = ["a", "b", "c"];
for (let item of arr) {
console.log(item);
}
// a b c
实际上,for-of 语句不仅可以循环遍历数组对象。
还可以迭代 Array、Map、Set、String 等对象。
// 遍历String
let str = "Hello";
for (let value of str) {
console.log(value)
}
// H e l l o
// 遍历Map
let iterable = new Map([["a", 1], ["b&#