简体   繁体   English

如何向对象添加一个空数组?

[英]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 点表示法和方括号表示法之间的上下文切换使我蒙蔽了我,我完全没想起在我的第三个区块中-animal [noises](忘记了“”)试图访问属性噪音的属性值,而我没有在我的对象中创建

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]; 就像您在使用animal[noises]; it means when you are trying to read data from the object. 这意味着当您尝试从对象读取数据时。

For animal[noises] , 对于animal[noises]

  • animal is the object animal是对象
  • and noises is the key/property of the object animal noisesanimal的关键/属性

And an array cannot be a key. 而且数组不能是键。 If you want to put noises array in animal object you can do it as follows, 如果要将noises数组放入animal对象中,可以按以下步骤进行操作,

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 []表示法用于获取需要用引号引起来的对象的属性。 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 . 该链接对数组和点表示法有很好的解释

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

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