for…in
for...in
语句以任意顺序遍历一个对象的除 Symbol 以外的可枚举属性,包括继承的可枚举属性。
基本用法:
const cat = {
name: "Tom",
age: 100,
};
const color = Symbol("color");
cat[color] = "pink";
console.log(cat); // { name: "Tom", age: 100, Symbol(color): "pink" }
for (let key in cat) {
console.log(key);
}
/**
* name
* age
*/
继承的属性也会被遍历:
const animal = {
color: "pink",
};
function Cat() {
this.name = "Tom";
}
Cat.prototype = animal;
const cat = new Cat();
for (let key in cat) {
console.log(key);
}
/**
* name
* color
*/
只输出本身的属性:
for (let key in cat) {
if (cat.hasOwnProperty(key)) {
console.log(key);
}
}
/**
* name
*/
for…of
for...of
语句遍历可迭代对象定义要迭代的数据。(包括 Array、Map、Set、String 等)
迭代 Array:
let arr = [1, 2, 3, 4];
for (let value of arr) {
console.log(value); // 1, 2, 3, 4
}
迭代 Map
const map = new Map([
[1, "a"],
[2, "b"],
[3, "c"],
]);
console.log(map); // Map(3) {1 => 'a', 2 => 'b', 3 => 'c'}
for (let value of map) {
console.log(value); // [1, 'a'] [2, 'b'] [3, 'c']
}
迭代 Set:
const set = new Set([1, 2, 3, 4])
console.log(set); // Set(4) {1, 2, 3, 4}
for (let value of set) {
console.log(value); // 1 2 3 4
}
迭代 String:
let string = 'hello';
for (let value of string) {
console.log(value); // h e l l o
}
区别
无论是for...in
还是for...of
语句都是迭代一些东西。它们之间的主要区别在于它们的迭代方式:
for...in
语句可以任意顺序迭代对象的可枚举属性。
for...of
语句遍历可迭代对象定义要迭代的数据。
for...of
循环和for...in
循环在遍历 Array 时的区别:
const arr = ['a', 'b', 'c', 'd'];
for (let value of arr) {
console.log(value); // a b c d
}
for (let key in arr) {
console.log(key); // 0 1 2 3
}
for...in
是为遍历对象属性而构建的,不建议与数组一起使用,数组可以使用forEach()
和for...of
。