美文网首页
[js]Property names and square b

[js]Property names and square b

作者: 清水芦苇 | 来源:发表于2017-08-21 10:22 被阅读6次

问题缘起

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

相关文章

网友评论

      本文标题:[js]Property names and square b

      本文链接:https://www.haomeiwen.com/subject/echcdxtx.html