您能告诉我这是什么类型的数据吗?我知道这是关键和价值观的对象,但具体是什么:pets[name]: "felix"
{name: "alex", pets[name]: "felix", pets[type]:"dog"}
pets[name]
和pets[type]
?答案 0 :(得分:2)
您引用的内容不是有效的JavaScript语法,它会因pets[name]
部分而中断,因为属性初始值设定项的属性名称部分必须是文字,字符串,数字或计算属性名称(ES2015 - 仅限“ES6” - ),pets[name]
不适合任何类别。
在JavaScript中,正确的对象初始值设定项为:
var o = {
name: "alex",
pets: {
name: "felix",
type: "dog"
}
};
你可以像这样访问这些信息:
console.log(o.name); // "alex"
console.log(o.pets.name); // "felix"
console.log(o.pets.type); // "dog"
但,名称pets
表明它可以容纳多个宠物;以上只允许一个。为了允许许多,我们使用一个对象数组而不是一个对象:
var o = {
name: "alex",
pets: [
{
name: "felix",
type: "dog"
},
{
name: "fluffy",
type: "cat"
}
]
};
访问数组条目使用索引:
console.log(o.name); // "alex"
console.log(o.pets[0].name); // "felix"
console.log(o.pets[0].type); // "dog"
console.log(o.pets[1].name); // "fluffy"
console.log(o.pets[1].type); // "cat"
以下是属性初始值设定项中有效属性名称的示例:
var name = "foo";
var sym = Symbol(); // <== ES2015+
var o = {
literal: "A literal, anything that's a valid IdentifierName can be used",
"string": "A string, any valid string can be used",
'string2': "Another string, just using single quotes instead of doubles",
10: "Numbers are valid, they're converted to strings",
10.5: "Even fractional numbers are allowed",
[name]: "A computed property name, valid in ES2015+ only; the name of this" +
"property is 'foo' because the `name` variable has `foo`",
["a"+"b"]: "Computed property names really are *computed*, this one is 'ab'",
[sym]: "Another computed property name, this one uses a Symbol rather than" +
"a string"
};
在上面,所有属性名称都是字符串,但使用Symbol
(ES2015 +)的字符串除外。