gpt4 book ai didi

javascript - "for ... in"循环 JavaScript - 它是否包含符号属性

转载 作者:行者123 更新时间:2023-12-03 09:49:35 27 4
gpt4 key购买 nike

MDN 说

A for...in loop only iterates over enumerable, non-Symbol properties.



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

但我做了一个简单的测试,它表明即使 Symbol 属性也在“for...in”循环中迭代。

这里有什么问题?
我错过了什么?

示例 1:

var symbol = Symbol("test");

function Animal(name){
this.name = name;
}

Animal.prototype = {};
Animal.prototype.constructor = Animal;

function Dog(breed){
this.breed = breed;
this.name = "Dog";
this.s = symbol;
}

Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;

console.log("001");
var d = new Dog("Sharo");
for (let x in d){
console.log(x, ":", d[x]);
}

console.log("002");
d = new Object();
for (let x in d){
console.log(x, ":", d[x]);
}

console.log("003");
d = new Number(5);
for (let x in d){
console.log(x, ":", d[x]);
}

最佳答案

for-in忽略符号- 键控 属性,而不是由值为 Symbol 的字符串键入的属性. for-in根本不注意属性(property)的值(value)。

例如,这个 for-in循环从不执行它的主体:

const obj = {
[Symbol("x")]: "foo"
};
for (const name in obj) {
console.log(`name = ${String(name)}`); // never runs
}
console.log("End of script");


但是这个有,因为该属性的 关键 是一个字符串,只是它的 值(value) 是一个符号:

const obj = {
foo: Symbol("x")
};
for (const name in obj) {
console.log(`name = ${name}`);
}
console.log("End of script");

关于javascript - "for ... in"循环 JavaScript - 它是否包含符号属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436388/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com