将键值对添加到 javascript 对象,其中键是一个对象

Adding key-value pair to javascript object where key is an object

1) 我正在尝试将一系列键值对添加到 JS 普通对象,其中键本身是一个对象。每次我添加一个键值对时,对象都会被覆盖(见 live here)。

var x = {};

var y = {
  'name': 'cat',
  'note': 'lazy animal'
}
var yy = 'meow'

x[{
  'name': 'dog',
  'note': 'loyal animal'
}] = 'bhow'
x[y] = yy

for(var k in x) {
  console.log(k);
  console.log(x[k]);
}

控制台输出:

"[object Object]"
"meow"

2) 当键是一个字符串时,这种(覆盖行为)不会发生(见 live here)。

var x = {};

var y = 'cat'
var yy = 'meow'

x['dog'] = 'bhow'
x[y] = yy

for(var k in x) {
  console.log(k);
  console.log(x[k]);
}

控制台输出:

"dog"
"bhow"
"cat"
"meow"

想了解为什么会这样吗?

我通过解决其他问题 (here) 想出了一些解决方案。但我无法理解这里的概念。任何指导将不胜感激。

对象键必须是字符串(或符号),因此当您尝试将对象用作键时,它首先将其转换为字符串表示形式,您已经看到了"[object Object]"

可以 但是通过重写对象上的 toString 函数来做你想做的事,只要你 return 一个唯一的字符串对于每个对象(可能是对象内容的散列),您的代码将按预期工作,因为它将使用 toString 函数来获取对象的字符串表示形式,并将其用作键:

var x = {};

var y = {
  'name': 'cat',
  'note': 'lazy animal',
  toString: function() {
    return 'yobj';
  }
};
var yy = 'meow';

x[{
  'name': 'dog',
  'note': 'loyal animal',
  toString: function() {
    return 'xobj';
  }
}] = 'bhow';
x[y] = yy;

for (var k in x) {
  console.log(k);
  console.log(x[k]);
}


正如 Jared 在 , the Map object (introduced with ES6 last year) is in part designed to solve this problem, and allows you to use objects directly as your keys if you're running in an environment that supports its use 中提到的那样。

任何时候你将一些东西传递给一个对象的 属性 访问器(object[...] 语法),它会被转换成一个字符串(参见 here 下的 "Property names" ).

普通 Javascript 对象(如您正在使用的对象)使用 the default toString() 方法类型转换为字符串,即 returns "[object Object]"。这就是为什么它们最终都指向相同的值。