简体   繁体   中英

what kind of a data is this in javascript?

  1. Can you tell me what type of a data this is? I know it is object with key and values but what exactlt is this: pets[name]: "felix"

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

  2. How do I retrieve the values of pets[name] and pets[type] ?

What you've quoted is not valid JavaScript syntax, it breaks as of the pets[name] portion, because the property name part of a property initializer must be either a literal, a string, a number, or a computed property name (ES2015 — aka "ES6" — only), and pets[name] doesn't fit any of those categories.

In JavaScript, the correct object initializer would be:

var o = {
    name: "alex",
    pets: {
        name: "felix",
        type: "dog"
    }
};

You'd access that information like this:

console.log(o.name);      // "alex"
console.log(o.pets.name); // "felix"
console.log(o.pets.type); // "dog"

However , the name pets suggests that it could hold more than one pet; the above only allows for one. To allow for many, we'd use an array of objects rather than just one object:

var o = {
    name: "alex",
    pets: [
        {
            name: "felix",
            type: "dog"
        },
        {
            name: "fluffy",
            type: "cat"
        }
    ]
};

Accessing the array entries uses indexes:

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"

Here are examples of valid property names in property initializers:

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"
};

In the above, all of the property names are strings except the one using Symbol (ES2015+).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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