[js]Property names and square brackets

问题缘起

var exists={
    1 : true
}
console.log(exists[{toString:()=>1}])
//true

自己的分析

难道做了隐式转换?(后来发现这根本不叫隐式转换)

查到解释

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

[js]Property names and square brackets_第1张图片
MDN 针对这件事的解释

拓展思考

这么说数组的下标,其实也是属性名,只是数组是js内置的特殊数据结构,所以它在chrome上表现成这个样子。其实本质就是一个多了length属性,__proto__指向Array.prototype的对象
比如:[1,2,3][1]===[1,2,3]['1']等价的,1是number,会执行toString方法转换成'1'

[js]Property names and square brackets_第2张图片
数组本质就是一个多了length属性,`__proto__`指向Array.prototype的对象

参考文献

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
  2. http://2ality.com/2013/04/quirk-implicit-conversion.html

你可能感兴趣的:([js]Property names and square brackets)