[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.

MDN 针对这件事的解释

拓展思考

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

数组本质就是一个多了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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容