我知道什么是a。在循环中(它在键上迭代),但我听说for…的第一次(它遍历值)。
我对……感到困惑。的循环。
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"
// it doesn't log "3", "5", "7", "hello"
}
我理解为……Of迭代属性值。那为什么它记录的不是"3" "5" "7" "hello"而是"3" "5" "7"
不像……循环中,遍历每个键("0","1","2","foo"),也遍历foo键,for…Of不会遍历foo属性的值,即“hello”。为什么会这样?
在此我为……的循环。它应该日志“3”,“5”,“7”,“你好”,但日志“3”,“5”,“7”。为什么?
例子链接
为…In语句以任意顺序遍历对象的可枚举属性。
可枚举属性是那些内部[[Enumerable]]标志被设置为true的属性,因此如果原型链中有任何可枚举属性,for…In循环也会迭代这些。
为…语句对iterable对象定义的要迭代的数据进行迭代。
例子:
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
let iterable = [3, 5, 7];
for (let i in iterable) {
console.log(i); // logs: 0, 1, 2, "arrCustom", "objCustom"
}
for (let i in iterable) {
if (iterable.hasOwnProperty(i)) {
console.log(i); // logs: 0, 1, 2,
}
}
for (let i of iterable) {
console.log(i); // logs: 3, 5, 7
}
像前面一样,你可以跳过添加hasOwnProperty在…的循环。
我在迭代器和生成器中找到了完整的答案(虽然它适用于TypeScript,但也适用于JavaScript)
Both for..of and for..in statements iterate over lists; the values
iterated on are different though, for..in returns a list of keys on
the object being iterated, whereas for..of returns a list of values
of the numeric properties of the object being iterated.
Here is an example that demonstrates this distinction:
let list = [4, 5, 6];
for (let i in list) {
console.log(i); // "0", "1", "2",
}
for (let i of list) {
console.log(i); // "4", "5", "6"
}
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.
let pets = new Set(["Cat", "Dog", "Hamster"]);
pets["species"] = "mammals";
for (let pet in pets) {
console.log(pet); // "species"
}
for (let pet of pets) {
console.log(pet); // "Cat", "Dog", "Hamster"
}