for…in
The for…in statement iterates the properties of a
对象
exceptSymbol
in any order, including inherited ones. Enumerable properties. for...in is constructed for traversing objects可枚举
属性
use:
let obj = {
a: 1,
b: 2,
c: 3,
};
for (let key in obj) {
console.log(key, obj[key]);
}
// 输出: a 1, b 2, c 3
1. Iterate one in any order对象
for in can also iterate over arrays because arrays are also objects.
不推荐用for...in迭代一个关注索引顺序的Array,因为for...in是以任意顺序迭代的
2. Iterable attributes other than Symbol
可枚举
let obj = {
a: 1,
[Symbol('d')]: 2, // 不可迭代Symbol属性
c: 3,
d: 4
};
Object.defineProperty(obj, 'c', {
enumerable: false // 不可迭代不可枚举属性
});
for (let key in obj) {
console.log(key, obj[key]);
}
// 输出: a 1, d 4
3. Inherited enumerable properties can be enumerated
let obj = {
a: 1,
b: 2
};
Object.prototype.c = 3; // 继承的可枚举属性
Object.defineProperty(obj, 'a', {
enumerable: false
});
for (let key in obj) {
console.log(key, obj[key]);
}
// 输出: b,2 c 3
4. Iteration focuses on attributes
for (let key in obj) {
}
for (let index in arr) {
}
// 开头已经说了for...in是遍历对象属性而构建的,所以获取值需要obj[key]/arr[index]
for…of
The for…of statement creates an iteration loop on
可迭代对象
, calls the custom iteration hook, and executes the statement for each distinct property value.
Iterable object: There must be a property with the key [Symbol.iterator]
on the object or prototype chain. Iterable objects include:
- Map
- Set
- Array
- TypeArray (Array-like)
- String
use:
// 迭代map
const map = new Map([
[{
a: 1}, 'a'],
[{
b: 2}, 'b'],
[{
c: 3}, 'c'],
]);
for (let [key, value] of map) {
console.log(key, value); // 输出: { a: 1 } a, { b: 2 } b, { c: 3 } c
}
// 迭代set
const set = new Set([1, 2, 3, 4]);
for (let value of set) {
console.log(value); // 输出: 1,2,3,4
}
// 迭代Array
const arr = [1, 2, 3, 4];
for (let value of arr) {
console.log(value); // 输出: 1,2,3,4
}
// 迭代类数组
function typeArray() {
for (let value of arguments) {
console.log(value); // 输出: 1,2,3,4
}
}
typeArray(1,2,3,4);
// 迭代string
const str = '1234';
for (let value of str) {
console.log(value); // 输出: 1,2,3,4
}
You can see that the values iterated out by for...of are all values, which means that for...of focuses on values.
Summarize
- usage scenarios: for...in is used to iterate objects, and for...of is used to iterate arrays. The object does not have
Symbol.iterator
attributes, so you cannot use for...of, but because the array is also an object, you can use for...in - In the iteration process: for...in will iterate the iterable properties and methods on its own prototype chain, but for...of will not
- Iteration results: for...in gets the key, for...of gets the value