问题
Can somebody explain the behaviour of the following code?
let obj = {a:1, b:2}
let i = ['a']
console.log(obj[i])
>> 1
Why is it that even an array can be used to access a property inside an object? As a side note this only works with an array of length 1. I have tried researching this but there's no documentation as far as I know that explains why this should work.
回答1:
Property names are always strings or symbols.
If you pass something which isn't a string or symbol, it gets converted to a string.
The default toString()
method on an array is roughly:
String.prototype.toString = function () { return this.join(","); }
So ['a']
gets converted to 'a'
.
As a side note this only works with an array of length 1.
It works fine with arrays that are longer. You just need a matching value:
const o = {
"a,b": "Hello"
}
const a = ["a", "b"];
console.log("" + a);
console.log(o[a]);
And since any object can be converted to a string, and you can customise the toString
method, you can do really weird things:
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]);
(Note that doing really weird things is usually a stupid idea that makes it hard to debug your own code two weeks later).
回答2:
let obj = {a:1, b:2}
First you declare an object with 2 properties, a and b with values 1 and 2, respectively.
let i = ['a']
Then a variable i is declared, with it's value set to a string array with a single element, 'a'.
console.log(obj[i])
In this statement, the value of i is resolved to a string because the array only contains one element, as you mentioned. Due to this, 'a' is a valid property name for obj because all object properties are either strings, and if you pass something such as an array, it's converted to a string.
If you reference the variable i
containing the array, and it has multiple elements, it cannot resolve to a single property name without you being more explicit such as obj[i[0]]
. If you only have one value, it'll resolves to that value.
obj['a']
is a valid property
obj['a,b']
is not.
来源:https://stackoverflow.com/questions/55119963/why-can-i-access-object-property-with-an-array