在JavaScript中,如果key []是一个对象,为什么object [key]不等于key? [英] Why is object[key] not equal to key, if key is an object, in JavaScript?

查看:68
本文介绍了在JavaScript中,如果key []是一个对象,为什么object [key]不等于key?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 .

I tested the code above and get false. If I try console.log(c[a] === b), then true is printed.

为什么?

推荐答案

此处的问题与如何设置 Object 的键有关.来自 MDN :

The problem here has to do with how an Object's keys are set. From MDN:

参数

nameValuePair1,nameValuePair2,... nameValuePairN

  • 两对名称(字符串)和值(任何值),其中名称与值之间用冒号分隔.

  • 任何值.

可以通过三种方式(通过相应的键)访问对象的值:

An object's values can be accessed (via the appropriate key) in three ways:

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 作为键.

When using bracket notation, you need to mind the gap...between the brackets! Objects set their keys and values using the toString method, unless they're passed a string (then there's no point in toString). When using the dot notation, they use .key as the 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中,如果key []是一个对象,为什么object [key]不等于key?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆