Reputation: 155
const items = ['one'];
const obj = {
'one': 'foobar'
};
console.log(obj[items]);
The console output is "foobar".
Why/how does [items]
evaluate to "one"? Will this throw an error in strict mode?
Upvotes: 2
Views: 31
Reputation: 17589
You cannot have a key of type Array. So your array is converted to string first and code is equivalent to
const items = ['one'];
const obj = {
'one': 'foobar'
};
console.log(obj[items.toString()]);
Interestingly it would not work if you will try to add Symbol
to your items array.
Also, because of the way Array.toString works, you can have items
with multiple elements, and still get the same behaviour:
const items = [1,2];
const obj = {
'1,2': 'foobar'
}
console.log(obj[items]); // also works
Upvotes: 4