for...in & for...of in JS

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stanxl/article/details/80960706
these 2 ways to loop through objects 
for...in will loop through property names
for...of will loop through property values

let person = {fname:"Stan", lname:"Xu",arms:2};
let arr = [3,5,7];
arr.foo = "hello";

let text = "";
for(let x in person){
    text += person[x];
    console.log(x); // fname, lname, arms
}
console.log(text); //StanXu2

//for...of will not work on person because person is not iterable
//for...in loops through innumerable properties
//for...of loops through iterable objects,such as Array/Map/Set

for(let x in arr){
    console.log(x); // "0","1","2","foo"
}

for(let x of arr){
    console.log(x); // 3, 5, 7
}

猜你喜欢

转载自blog.csdn.net/stanxl/article/details/80960706