Why is object[key] not equal to key, if key is an object, in JavaScript?

后端 未结 3 1095
我在风中等你
我在风中等你 2020-12-09 08:52
var a = new Object;
var b = new Object;
var c = new Object;

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

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

I tested the code above and get fa

3条回答
  •  心在旅途
    2020-12-09 09:14

    Object is not a valid key for JavaScript Object, only strings are

    So, when you do this:

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

    The compiler can not use the a or b as a key for c as in c[a] or c[b].

    However, it does not fail, because JavaScript can work around this problem. First it figures out that

    1. The variable is an object and
    2. The variable has toString -function

    Thus, the JavaScript compiler will call toString() of each of those variables. And by default, the Object.prototype.toString it will return "[object Object]" -string, because the implementation is the default implementation which does that and that value becomes the new key

    c["[object Object]"] = a;
    c["[object Object]"] = b; // overrides the previous
    

    Which is not what you wanted. The problem is that toString will by default return always the same value, so assigments will always go to the same key.

    To demonstrate that toString is actually the problem, you can actually do a horrible cheat to make each object return unique string

    // don't do this!!! 
    (function() {
      var id=1;
      Object.prototype.toString = function() {
       if(!this._id) this._id = id++;
       return "Object"+this._id;
      }
    }());
    

    After that key of c[a] will be c["Object1"] and c[b] will be c["Object2"] and so on... and the c[a] == a and c[b] == b are working as expected, but in real life this is not a good solution.

    An acceptable way to solve this would be either use some other key, perhaps an ID assigned to the object like c[a.id] = a or to use ES6 Map Object, where any value, including Objects, can be used as a key.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

    The Map object is a simple key/value map. Any value (both objects and primitive values) may be used as either a key or a value.

提交回复
热议问题