gpt4 book ai didi

javascript - 问题使用键名访问 JSON 对象。但适用于 []

转载 作者:行者123 更新时间:2023-11-29 16:49:17 28 4
gpt4 key购买 nike

使用 .给出错误但使用 [] 它有效吗?访问 JSON 对象键的正确语法是什么?

此语法给出错误:

var obj2G = obj.2G;

此语法有效,但为什么需要以这种方式访问​​?

var obj2G = obj["2G"];

var obj = {
"2G": [{
"essid": "SINGTEL-662F",
"authmode": "psk psk2",
"authkey": "0000026159",
"isEnable": "1",
"isHidden": "0",
"hwaddr": "E0:8E:3C:00:66:30",
"opmode": "ap"
}, {
"essid": "GUEST1-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "",
"opmode": "ap"
}, {
"essid": "GUEST2-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "",
"opmode": "ap"
}, {
"essid": "GUEST3-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "62:8E:3C:00:66:33",
"opmode": "ap"
}],
"5G": [{
"essid": "SINGTEL-662F(5G)",
"authmode": "psk psk2",
"authkey": "0000026159",
"isEnable": "1",
"isHidden": "0",
"hwaddr": "E0:8E:3C:00:66:31",
"opmode": "ap"
}, {
"essid": "GUEST1(5G)-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "6a:8e:3c:00:66:32",
"opmode": "ap"
}, {
"essid": "GUEST2(5G)-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "",
"opmode": "ap"
}, {
"essid": "GUEST3(5G)-662F",
"authmode": "psk psk2",
"authkey": "aabbccddee",
"isEnable": "0",
"isHidden": "0",
"hwaddr": "6a:8e:3c:00:66:30",
"opmode": "ap"
}]
}

obj2G = obj["2G"];
console.log(obj2G);

obj2G = obj.2G;
console.log(obj2G);

最佳答案

如果您使用点符号:

property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

在这种情况下,您必须使用括号表示法:

property_name is a string. The string does not have to be a valid identifier; it can have any value, e.g. "1foo", "!bar!", or even " " (a space).

请参阅文档:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors

值得一提的是,如果要使用变量访问属性,则必须使用括号表示法。例如:

var myName = "foo";
var myObject = { foo: 42};
console.log(myObject.myName);//returns undefined

但是:

var myName = "foo";
var myObject = { foo: 42};
console.log(myObject[myName]);//returns 42

关于javascript - 问题使用键名访问 JSON 对象。但适用于 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37783841/

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