gpt4 book ai didi

javascript - 在 JavaScript 中,如果 key 是一个对象,为什么 object[key] 不等于 key?

转载 作者:行者123 更新时间:2023-12-03 02:04:57 25 4
gpt4 key购买 nike

var a = new Object;
var b = new Object;
var c = new Object;

c[a] = a;
c[b] = b;

console.log(c[a] === a);

我测试了上面的代码并得到false。如果我尝试 console.log(c[a] === b),则会打印 true

为什么?

最佳答案

这里的问题与对象的键的设置方式有关。来自 MDN :

Parameters

nameValuePair1, nameValuePair2, ... nameValuePairN

  • Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.

value

  • Any value.

可以通过三种方式访问​​对象的值(通过适当的键):

var o = {};
var key = "fun";

// method 1:
o[key] = "the key will be equal to `key.toString()"
// method 2:
o.key = "the key will be equal to 'key'"
// method 3:
o["key2"] = "the key will be equal to `key2`"
/*
{
"fun" : "the key will be...", // method 1
"key" : "the key will be...", // method 2
"key2": "the key will be..." // method 3
}
*/

使用括号表示法时,您需要注意括号之间的间隙!对象使用 toString 设置它们的键和值方法,除非它们传递一个字符串(那么 toString 就没有意义)。当使用点表示法时,他们使用 .key 作为键。

让我们看看您的案例:

var a = {}
, b = {}
, c = {}
;

c[a] = a;
// `a` is not a string, and we're using brackets, so the key
// will be equal to `key.toString()`:
// a.toString() === "[object Object]"
// Try the following in your console: `{}.toString()`
// Note how this is different from console.log({}), since
// the console exposes your object (that's why the dev console is useful)
// c is now: `{ "[object Object]" : a }`

c[b] = b;
// b is also an object, so `b.toString()` is the same as `a.toString()`
// that means c is now `{ "[object Object]" : b }`

assert c[a] === a
// a.toString() == b.toString() == "[object Object]"
// and we just noted that c was `{ "[object Object]" : b }`
// so of course this is false
assert c[b] === b
// true because c[b] == b;
assert c["[object Object]"] === b;
// also true
assert c.b === b
// false, since `c` has no "b" key (c.b is `undefined`)

关于javascript - 在 JavaScript 中,如果 key 是一个对象,为什么 object[key] 不等于 key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30136094/

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