简体   繁体   中英

How to add an empty array to object?

I'm having trouble adding my empty array into my object via the bracket notation method. I know how to get my empty array into the object via dot notation, but I just don't understand why the bracket notation isn't working for me.

Update : I understand my problem now; the context switch between dot notation & bracket notation blinded me & I completely failed to recall that in my 3rd block - animal[noises] (forgot the "") was trying to access the property value of the property noises, which I hadn't created yet in my object

Creating & adding properties to my object

var animal = {};
animal.username = "Peggy";
animal["tagline"] = "Hello";

Which will then create this:

animal {
      tagline: "Hello",
      username: "Peggy"
}

Why won't the following work when I'm trying to add it into my object?

var noises = [];
animal[noises];

I'm getting this in my console (same as above):

animal {
      tagline: "Hello",
      username: "Peggy"
}

I was able to get my result this way:

animal.noises = [];

Which outputs this into my console:

animal {
  noises: [],
  tagline: "Hello",
  username: "Peggy"
}

But that still leaves me with the question: why doesn't this work via bracket notation?

Use

animal.noises = noises;

or

animal['noises'] = noises;

As when you are using animal[noises]; it means when you are trying to read data from the object.

For animal[noises] ,

  • animal is the object
  • and noises is the key/property of the object animal

And an array cannot be a key. If you want to put noises array in animal object you can do it as follows,

animal['noises'] = noises;

In your case you have to try

animal['noises']=noises

Array [] notation is used to get property of an object that requires a quote around it. Array notations are commonly used to get identifiers of objects having special characters included.say,

   var animal={
      "@tiger":'carnivore' // you can't have @tiger without quote as identifier
   } 
  console.log(animal.@tiger) // it will give ERROR
  console.log(animal['@tiger']) // it will print out  'carnivore'

this link has good explanation on array and dot notation .

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