In development, we often traverse arrays or objects, commonly used methods such as for, foreach, for in, for of, so today we will discuss the usage of these methods; 1.
for loop:
for loop is often used in In the array, the usage is also very simple
for(let i=0,len=array.length;i<len;++i){
console.log(array[i])
}
In this way, each item in the array can be traversed, and the loop
can be ended by break or return; why can’t it traverse the object? Obviously, the object does not have the length property.
2. Foreach loop:
array.foreach((item,index)=>{
console.log(item,index)
)}
The writing method is more concise than for, but the biggest difference between it and for is that it cannot use break or return to break out of the loop; if you must break out of the loop, you have to use try...catch...
try{
array.foreach((item,index)=>{
if(some===item){
throw error
}
)}
}catch(error){
}
3.for in is usually used to traverse objects
const obj={
a:1,b:2}
for(let key in obj){
console.log(key ,obj[key]) //a ,1 b ,2
}
Of course, in addition to traversing the properties of the object itself, you can also traverse the properties on the object prototype, for example:
const obj={
a:1,b:2}
obj.prototype.c=3;
for(let key in obj){
console.log(key ,obj[key]) //a,1 b,2 c,3
}
But what if we use this to traverse the array?
const array=[1,2,3,4]
for(let key in array){
console.log(key ,array[key]) //0,1 1,2 2,3 3,4
}
Arrays are also objects in nature, so arrays also have prototypes. Suppose we also add attributes to the prototype of the array, for example:
const array=[1,2,3,4];
array.prototype.addPrototype=5;
for(let key in array){
console.log(key ,array[key]) //0,1 1,2 2,3 3,4 addPrototype,5
}
4. For of When the prototype method or attribute is added to the array, we don't want to traverse the method on the prototype, then ES6 provides such a method, mainly to make up for the defects of for in;
const array=[1,2,3,4];
array.prototype.addPrototype=5;
for(let key of array){
console.log(key ,array[key]) //0,1 1,2 2,3 3,4
}
But for of cannot be used to traverse objects directly, otherwise it will report "obj is not iterable". If we want to use this to traverse objects, we have to use the Object.keys() method
const obj={
a:1,b:2}
for(let key of Object.keys(obj)){
console.log(key)
}
Summary:
1. The most powerful function is for in, which can traverse both arrays and objects;
2. Except foreach can’t use break or return to jump out of the loop, everything else is
fine ; 3. for in is usually used to traverse Objects, the others are traversal arrays