This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Everything in JS is an object. If you want to traverse an object, what are the possible ways?
for in
First, the proverbial for… in
for… The IN statement iterates through an object’s enumerable properties other than Symbol in any order, including inherited enumerable properties.
const obj = {
name: "nordon".age: 12
};
for (const key in obj) {
console.log(key, The '-', obj[key]);
}
Copy the code
Console output in sequence
name --- nordon
age --- 12
Copy the code
for… In traverses not only objects but also groups of numbers
const arr = ["a"."b"];
for (const key in arr) {
console.log(key, "-", arr[key]);
}
Copy the code
Console output in sequence
0 --- a
1 --- b
Copy the code
Although it can iterate over groups of numbers, it is not recommended because it is specifically designed to iterate over object properties and is not recommended with arrays, and arrays are similar to forEach, for… It is more suitable to use the “of” and “for” cycles together
for of
Use for… The of traversal object is opportunistic, as it is designed to iterate over objects that have iterables to use, such as Array, Set, Map, arguments
Want to use for… Of traversal object, we need to transform a common object into an iterable object, JS developers provide a lot of metaprogramming capabilities, @@iterator is one of them. Iterator objects have a Symbol. Iterator method by implementing the @@iterator method
const iteratorObj = {
*[Symbol.iterator]() {
yield 'name'
yield 'age'
},
name: "nordon".age: 12};for (const key of iteratorObj) {
console.log(key, "-", iteratorObj[key]);
}
Copy the code
Console output
name --- nordon
age --- 12
Copy the code
Object.keys
Keys returns an array of enumerable keys from an Object. Note that the array runs in the same order as normal traversal of the Object
const obj = {
name: "nordon".age: 12};Object.keys(obj);
Copy the code
Console output
['name', 'age']
Copy the code
You can retrieve the object’s data in turn by iterating through the array
Object.keys(obj).forEach(key= > {
console.log(key, The '-', obj[key]);
})
Copy the code
Object.entries
The Object.entries method returns key-value pairs of an Object’s own enumerable properties as an array
const obj = {
name: "nordon".age: 12};Object.entries(obj);
Copy the code
Console output
[["name","nordon"],["age",12]]
Copy the code
Returns a two-dimensional array that matches for… Of fetches the key of the object
for (const [key, value] of Object.entries(obj)) {
console.log(key, The '-', value);
}
Copy the code