【问题标题】:How to add an empty array to object?如何将空数组添加到对象?
【发布时间】:2015-03-16 02:20:30
【问题描述】:

我无法通过括号表示法将空数组添加到对象中。我知道如何通过点符号将我的空数组放入对象中,但我只是不明白为什么括号符号对我不起作用。

更新:我现在明白我的问题了;点符号和括号符号之间的上下文切换使我蒙蔽了我,我完全不记得在我的第三个块中-动物[噪声](忘记了“”)试图访问属性噪声的属性值,而我没有尚未在我的对象中创建

为我的对象创建和添加属性

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

然后创建这个:

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

当我尝试将其添加到我的对象时,为什么以下操作不起作用?

var noises = [];
animal[noises];

我在我的控制台中得到了这个(与上面相同):

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

我能够通过这种方式得到我的结果:

animal.noises = [];

将其输出到我的控制台:

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

但这仍然给我留下了一个问题:为什么这不能通过括号表示法工作?

【问题讨论】:

  • animal[noises]; 表示您正在尝试使用noises 给出的名称访问animal 的属性。您没有在那里创建任何属性。
  • 我刚刚更新了问题。看看第三个代码块
  • @CliffordFajardo 这不会改变任何东西。您没想到animal["Hello"]; 会创建一个名为tagline 的属性,其值为Hello,是吗?现在您为什么期望animal[[]](这实际上是您的尝试)应该创建一个名为noises 的属性?您显然不知道括号符号的含义,您应该在初学者 JavaScript 教程中查找它。

标签: javascript arrays object properties variable-assignment


【解决方案1】:

使用

animal.noises = noises;

animal['noises'] = noises;

当您使用animal[noises]; 时,这意味着您尝试从对象中读取数据。

【讨论】:

  • 谢谢。我也记不起括号符号我需要“”围绕噪音。您的回答简洁明了。
【解决方案2】:

对于animal[noises]

  • animal 是对象
  • noises 是对象animal 的键/属性

而且数组不能是键。如果您想将noises 数组放入animal 对象中,可以按如下方式进行,

animal['noises'] = noises;

【讨论】:

    【解决方案3】:

    在你的情况下,你必须尝试

    animal['noises']=noises
    

    Array [] 表示法用于获取需要在其周围加上引号的对象的属性。数组表示法通常用于获取包含特殊字符的对象的标识符。比如说,

       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.

    【讨论】:

    • 感谢您提供的简洁明了的示例!
    猜你喜欢
    • 1970-01-01
    • 2015-09-03
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2014-03-28
    相关资源
    最近更新 更多