for-in
for… The in statement iterates over the enumerable properties of an object other than Symbol in any order.
for (variable in object){
...
}
Copy the code
variable
: At each iteration,variable
It’s going to be assigned a different valuekey
, i.e.,The property name.object
:Symbol
The type ofCan be enumeratedThe object whose property is being iterated over.
for … In is more suitable for traversing objects and is not recommended for use with arrays because the traversal order may not be the index order of the actual array.
for … In iterates over all enumerable properties, including stereotypes:
const obj = { a: 1.b: 2.c: 3 };
function myObj() {
this.name = 'Jack';
}
myObj.prototype = obj;
const user = new myObj();
for (const prop in user) {
console.log(`user.${prop} = ${user[prop]}`);
}
// user.name = Jack
// user.a = 1
// user.b = 2
// user.c = 3
Copy the code
If you want to iterate only over its own properties, you need to use the hasOwnProperty() method to determine whether a property is an instance property of the object:
const obj = { a: 1.b: 2.c: 3 };
function myObj() {
this.name = 'Jack';
}
myObj.prototype = obj;
const user = new myObj();
for (const prop in user) {
if (user.hasOwnProperty(prop)) {
console.log(`user.${prop} = ${user[prop]}`); }}// user.name = Jack
Copy the code
for-of
for… The of statement creates an iterative loop over iterable objects (including Array, Map, Set, String, TypedArray, Arguments objects, etc.) and executes the statement for the value of each of the different attributes.
for (variable of iterable) {
...
}
Copy the code
variable
: In each iteration, the attributes of differentvalueAssigned tovariable
.可迭代
: An object whose properties are iteratively enumerated.
Unlike forEach(), it responds correctly to break, continue, and return statements.
Iterating over an array:
const arr = [10.20.30];
for (const value of arr) {
console.log(value);
}
/ / 10
/ / 20
/ / 30
Copy the code
Iterative Map:
const map = new Map([['a'.1],
['b'.2],
['c'.3]]);for (const entry of map) {
console.log(entry);
}
// ["a", 1]
// ["b", 2]
// ["c", 3]
for (const [key, value] of map) {
console.log(value);
}
/ / 1
/ / 2
/ / 3
Copy the code
Iterating over the Arguments object:
(function () {
for (const argument of arguments) {
console.log(argument);
}
})(1.2.3);
/ / 1
/ / 2
/ / 3
Copy the code
conclusion
for... in
Statement toAny orderOf an iterated objectkey, includingThe prototype. It is not recommended toAn array ofUse them together.for... of
Statements traversalIterable objectthevalue.