Property names are always either strings or symbols.
If you provide something that is not a string or symbol, it will be automatically converted to a string.
The default behavior of the toString()
method for an array can be simplified as:
String.prototype.toString = function () { return this.join(","); }
Therefore, ['a']
will be converted to 'a'
.
It should be noted that this conversion only works with arrays containing one element.
For arrays with more than one element, you need to have a matching value:
const o = {
"a,b": "Hello"
}
const a = ["a", "b"];
console.log("" + a);
console.log(o[a]);
Furthermore, since any object can be transformed into a string and the toString
method can be customized, unusual outcomes can be achieved:
const data = {
"42": "Hello"
}
class Weird {
constructor(x) {
this.x = x;
}
toString() {
return this.x + 40;
}
}
const w = new Weird(2);
console.log(data[w]);
(It's worth mentioning that engaging in these unconventional practices is generally ill-advised as it may result in difficulties while troubleshooting your code later on).