For...of vs For..in

For...In loops 可以遍历一个object的 keys.

const shark = {
    species: "great white",
    color: "white",
    numberOfTeeth: Infinity
}
// Print property names of object
for (attribute in shark) {
    console.log(attribute);
}

Output :
species
color
numberOfTeeth



For...Of Loop is a new feature of ES6.
可用于遍历一个可迭代的对象的值,比如array, string

// Initialize array of shark species
let sharks = [ "great white", "tiger", "hammerhead" ];

// Print out each type of shark
for (let shark of sharks) {
    console.log(shark);
}

Output :
great white
tiger
hammerhead


一个比较:

const str1 = "asdf"

for (const element of str1) {
  console.log(element);
}
console.log("------------");
const str2 = "asdf"

for (const element in str2) {
  console.log(element);
}

Output:
"a"
"s"
"d"
"f"


"0"
"1"
"2"
"3"


var arr = [3, 5, 7];
arr.foo = "hello";

for (var i in arr) {
  console.log(i); // logs "0", "1", "2", "foo"
}

for (var i of arr) {
  console.log(i); // logs "3", "5", "7"
}

Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values.

你可能感兴趣的:(For...of vs For..in)