为什么可以使用数组访问对象属性? [英] Why can I access object property with an array?
问题描述
有人可以解释以下代码的行为吗?
Can somebody explain the behaviour of the following code?
let obj = {a:1, b:2}
let i = ['a']
console.log(obj[i])
>> 1
为什么连一个数组都可以用来访问对象内部的属性?附带说明,这仅适用于长度为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.
推荐答案
Property names are always strings or symbols.
如果传递的内容不是字符串或符号,则会将其转换为字符串.
If you pass something which isn't a string or symbol, it gets converted to a string.
数组上默认的 toString()
方法大致为:
The default toString()
method on an array is roughly:
String.prototype.toString = function () { return this.join(","); }
因此 ['a']
被转换为'a'
.
请注意,这仅适用于长度为1的数组.
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]);
由于任何对象都可以转换为字符串,并且您可以自定义 toString
方法,因此您可以做一些奇怪的事情:
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).
这篇关于为什么可以使用数组访问对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!