Today I saw a book talking about JS objects, and there was an example that I didn’t quite understand
var myObject = {};
myObject[myObject] = "foo";
myObject["[object Object]"];//foo,这里的[object Object]等价于{}吗?
PHP中文网2017-05-18 10:53:26
The [object Object] here is obtained due to the implicit type conversion of myObject in this step myObject[myObject] = "foo";
, so the [object Object] here is just a converted string, but in the object as '[object Object]' stores the value 'foo' as the key!
PHP中文网2017-05-18 10:53:26
var myObject = {};
console.log(myObject.toString());//[object Object]
myObject[myObject] = "foo";
console.log(myObject["[object Object]"]);//foo,这里的[object Object]等价于{}吗?
console.log(myObject.toString());//[object Object]
for(var i in myObject){
console.log(i);//[object Object]
}
//从以上结果可以看出:不管这个对象是什么,转成字符串后都是"[object Object]""
世界只因有你2017-05-18 10:53:26
myObject[myObject]这里发生隐型转换,{}转换为字符串,调用toString()方法
({}).toString()//"[object Object]"
ringa_lee2017-05-18 10:53:26
This is an implicit conversion problem of object key names.
Take this example, explained in vernacular:
There is an A object, and I want to pass the B object in as a key name of the A object, but because all the key names of the object are strings, the B object will call the toString() method and convert it to a string "[ object Object]" to store data as a key name of an A object. The data in the instance is this "foo" string.
Another point that needs special attention is:
The A object and B object in your question are the same, which is very confusing, so I declared a new mykey to distinguish them.
var myObject = {};
var myKey={};
myObject[myKey]="foo";
console.log("[object Object]"===myKey.toString());//true
The printed result is true, which proves that "[object Object]" is not equal to {}, but is equal to the string returned by the object after passing the toString() method
console.log(myObject[myKey.toString()]);//foo
console.log(myObject["[object Object]"]);//foo
console.log(myObject[myKey.toString()]===myObject["[object Object]"]);//true
The above three lines of code prove again: "[object Object]" is equal to the string returned by the object after passing the toString() method