gpt4 book ai didi

JavaScript - 计算属性 - 深深的困惑

转载 作者:行者123 更新时间:2023-12-04 23:35:20 25 4
gpt4 key购买 nike

似乎我对 JavaScript 中的计算属性感到很困惑。

当我定义一个对象并将 [d] 作为一个键(作为属性键/名称)时,这个 [d] 实际上做了什么?似乎对于某些值 d 它计算 s = d.toString() 并使用该值 s 作为属性键。但是对于其他值 d(例如,当 d 是符号时)它实际上使用符号的值作为键。

所以 [d] 的这种双重行为(作为一种语法结构)似乎令人困惑。有人可以深入解释这是如何工作的吗?

顺便说一句,还有其他特殊情况吗?或者只是当我们有这种特殊行为时 d 是一个符号?

回到基础:什么事物可以是对象属性的键/名称?它只是字符串还是字符串和符号,或者还有其他一些东西......?

例子:

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]);
}

var d1 = {};
var d2 = {};

var d = new Dog("Sharo");

var m = {[d1] : 5, [d2] : 10, [d] : 20, z : 100, symbol: 2000, [symbol] : 5000};

console.log("============================");
console.log(m);

for (let x in m){
console.log(x, ":", m[x]);
}
console.log("============================");

最佳答案

由于似乎没有人有兴趣回答这个问题,我将根据我上面得到的评论自己回答,因此我不再感到困惑。

请注意,这里的答案是基于 ES6 的。我的意思是...谁知道 JavaScript 的 future 还会有什么 :)

When I define an object and I put [d] as a key (as a property key/name) what does this [d] actually do? Seems that for some objects d it calculates s = d.toString() and uses that value s as the property key. But for other objects d (e.g. when d is a Symbol) it uses really the Symbol's value as the key.

是的,没错。当 d 是 Symbol 时,直接使用它的值。当 d 不是 Symbol 时,它的值被强制转换为字符串,并且该字符串用作属性名称/键。强制转换更像是 String(d) 而不是 d.toString()

So this dual behavior of [d] (as a syntax construct) seems confusing. Could someone explain in depth how this works?

上面已经解释过了。

Are there other special cases btw? Or is it just when d is a Symbol when we have that special behavior?

没有其他“特殊情况”。从 ES6 开始,只有字符串和符号可以作为属性键。

Back to the basics: what things can be keys/names of properties of an object? Is it just strings or just strings and symbols or is there also something additional... ?

如前所述,从 ES6 开始,只有字符串和符号可以作为属性键。

引用资料:

(1) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

“属性名称是字符串或符号。任何其他值,包括数字,都被强制转换为字符串。”

(2) https://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey

关于JavaScript - 计算属性 - 深深的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436684/

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