假设我有以下对象:
{ "id": "109",
"No. of interfaces": "4" }
以下代码对于 "id" 键运行良好:
alert(obj.id); // Works fine!
但是如果键中有空格,那么我就无法使用点表示法访问它们的值,例如。
alert(obj."No. of interfaces"); // Syntax error
如何使用点表示法访问具有空格的键名的值?使用点表示法是否可能?还是必须使用其他方式?
假设我有以下对象:
{ "id": "109",
"No. of interfaces": "4" }
alert(obj.id); // Works fine!
alert(obj."No. of interfaces"); // Syntax error
如何使用点表示法访问具有空格的键名的值?使用点表示法是否可能?还是必须使用其他方式?
var test = {
"id": "109",
"No. of interfaces": "4"
}
alert(test["No. of interfaces"]);
更多信息请参见:
test['No. of interfaces']
而不是点表示法 test."No. of interfaces"
。 - benjakiconst { Pricing, Location, data[0]["Product 1"] } = data[0]
<< 不起作用const { Pricing, Location, ["Product 1"] } = data[0]
<< 不起作用 - VinnPardeep Jain的答案对于静态数据可能有用,但如果我们在JSON中有一个数组怎么办?
例如,我们有i个值,并获取id字段的值
alert(obj[i].id); //works!
但是如果我们需要带有空格的键怎么办?
在这种情况下,可以使用以下结构来帮助([]块之间不需要点号):
alert(obj[i]["No. of interfaces"]); //works too!
test
表达式的变体,这只会给话题增加噪音。那么f()["No. of interfaces"]
怎么样?((obj)[i])["No. of interfaces"]
呢?等等。 - Philippe-André Lorin