当前位置:网站首页>Difference between foreach, for... In and for... Of

Difference between foreach, for... In and for... Of

2022-06-11 06:21:00 Geek student

1. forEach, for in , for of Differences among the three ?

1.1 forEach

  • More concise when traversing , Efficiency and for identical , Don't worry about set subscripts , Reduce the efficiency of errors
  • no return value
  • Out of commission break Break the loop , Out of commission return Return to the outer loop
const array = [1, 3, 4];
let newArray = arr.forEach(i => {
    
    i += 1;
    console.log(i); //2,4,5
});
console.log(arr); //[1,3,4]
console.log(newArray); //undefined

1.2 for in

for…in Used to traverse arrays or object properties ( Most of them are object
Traversable The key name of the array , Traversing objects is simple and convenient

//  Traversing objects 
let person = {
     name: 'xiaosheng', age: 24, city: ' Shenzhen ' };
let text = '';
for (let i in person) {
    
    text += person[i];
}
//  The output is : zhleon24 Shenzhen 
//  Traversal array 
let arry = [1, 2, 3, 4, 5];
for (let i in arry) {
    
    console.log(arry[i]);
}
//  The output is  1,2,3,4,5

1.3 for of

ES6 reference C++、Java、C# and Python Language , Introduced for…of loop ,
for…of Can traverse all iteratable objects ( Include Array,Map,Set,String,TypedArray,arguments Object etc.

//  Array 
const arr = ['blueheart', 'zhleon', 'xiaosheng'];
for (let v of arr) {
    
    console.log(v); // blueheart zhleon xiaosheng
}

// Set
var names = new Set(['blueheart', 'zhleon']);
for (var e of names) {
    
    console.log(e);  // blueheart zhleon
}


//  Class array object  arguments
function printArgs() {
    
    for (let x of arguments) {
    
        console.log(x);
    }
}
printArgs('blueheart', 'zhleon'); // blueheart zhleon
原网站

版权声明
本文为[Geek student]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020527521253.html