繁体   English   中英

这在javascript中是什么类型的数据?

[英]what kind of a data is this in javascript?

  1. 你能告诉我这是什么类型的数据吗? 我知道它是带有键和值的对象,但具体是什么: pets[name]: "felix"

    {name: "alex", pets[name]: "felix", pets[type]:"dog"}

  2. 如何检索pets[name]pets[type]

您引用的不是有效的 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+) 的属性名称之外,所有属性名称都是字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM