gpt4 book ai didi

javascript - 为什么我可以使用数组访问对象属性?

转载 作者:数据小太阳 更新时间:2023-10-29 05:56:35 25 4
gpt4 key购买 nike

有人可以解释以下代码的行为吗?

let obj = {a:1, b:2}
let i = ['a']
console.log(obj[i])
>> 1

为什么甚至可以使用数组来访问对象内部的属性?作为旁注,这仅适用于长度为 1 的数组。我已经尝试对此进行研究,但据我所知,没有任何文档可以解释为什么这应该有效。

最佳答案

属性名称始终是字符串或 symbols .

如果您传递的不是字符串或符号,它会被转换为字符串。

数组上的默认 toString() 方法大致是:

String.prototype.toString = function () { return this.join(","); }

因此 ['a'] 被转换为 'a'

As a side note this only works with an array of length 1.

它适用于更长的数组。您只需要一个匹配值:

const o = {
"a,b": "Hello"
}
const a = ["a", "b"];
console.log("" + a);
console.log(o[a]);


而且由于任何对象都可以转换为字符串,并且您可以自定义 toString 方法,因此您可以做一些非常奇怪的事情:

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]);

(请注意,做非常奇怪的事情通常是一个愚蠢的想法,这会让两周后很难调试您自己的代码)。

关于javascript - 为什么我可以使用数组访问对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55119963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com