[英]Accessing object property through bracket notation regardless of the number of brackets
An object's properties can be accessed through bracket notation by doing the following:通过执行以下操作,可以通过括号表示法访问对象的属性:
let obj = {a: "test"}
obj["a"]
However, I was not aware that the same object's property could also be accessed by doing:但是,我不知道也可以通过以下方式访问同一对象的属性:
let v = ["a"] // An array
obj[v]
or或者
obj[["a"]]
or或者
obj[[[[[[[[[["a"]]]]]]]]]]
Just wondering, why is that?只是想知道,这是为什么呢?
I stumbled on this behaviour after storing an array into a variable and mistakingly using the variable/array, rather than the first item of the array, to access an object's property and surprisingly... it didn't throw an error but returned the value.在将数组存储到变量中并错误地使用变量/数组而不是数组的第一项来访问对象的属性后,我偶然发现了这种行为,令人惊讶的是……它没有抛出错误,而是返回了值.
All object keys are strings.所有 object 键都是字符串。 When you use bracket notation foo[bar]
the variable you try to fetch will be converted to a string:当您使用括号符号foo[bar]
时,您尝试获取的变量将被转换为字符串:
const bar = { toString() { return "hello"; } } const foo = { hello: "world" } console.log(foo[bar]);
When arrays are converted to a string, join(",")
is implicitly called on them.当 arrays 转换为字符串时,会在它们上隐式调用join(",")
。 And if an array has a single value, the result is the single value as a string:如果数组只有一个值,则结果是字符串形式的单个值:
const arr = ["hello"]; console.log(arr.toString()); console.log(String(arr)); console.log(arr.join(","));
If you have nested arrays, each with one item, you'd still get a single string out of the conversion, since join()
also converts all the members into strings, so with String([["hi"]])
you (roughly) get:如果你嵌套了 arrays,每个都有一个项目,你仍然会从转换中得到一个字符串,因为join()
也会将所有成员转换为字符串,所以使用String([["hi"]])
你(大致)得到:
[["hi"]].join(",")
-> String(["hi"])
-> ["hi"].join(",")
-> String("hi")
[["hi"]].join(",")
-> String(["hi"])
-> ["hi"].join(",")
-> String("hi")
So, if you supply an array as a key, it works, as long as you only have a single value in each array:因此,如果您提供一个数组作为键,它就可以工作,只要您在每个数组中只有一个值:
const foo = { hello: "world" }; const arr = [[["hello"]]]; console.log(foo[arr]); console.log(foo[String(arr)]); console.log(foo[arr.toString()]); console.log(foo[arr.join(",")]);
console.log(['a'].toString()); // "a"
It's because a key needs to be a string and javascript does type coercion, converting the array to a string automatically.这是因为一个键需要是一个字符串,并且 javascript 确实类型强制,将数组自动转换为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.