Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何向对象添加空数组?_Javascript_Arrays_Object_Properties_Variable Assignment - Fatal编程技术网

Javascript 如何向对象添加空数组?

Javascript 如何向对象添加空数组?,javascript,arrays,object,properties,variable-assignment,Javascript,Arrays,Object,Properties,Variable Assignment,我无法通过括号表示法将空数组添加到对象中。我知道如何通过点符号将空数组放入对象中,但我不明白为什么括号符号对我不起作用 更新:我现在明白我的问题了;点表示法和括号表示法之间的上下文切换使我失明&我完全无法回忆起在我的第三个块中,animal[noises](忘记了“”)试图访问属性noises的属性值,而我还没有在我的对象中创建属性noises var animal = {}; animal.username = "Peggy"; animal["tagline"] = "Hello"; 创建

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

更新:我现在明白我的问题了;点表示法和括号表示法之间的上下文切换使我失明&我完全无法回忆起在我的第三个块中,animal[noises](忘记了“”)试图访问属性noises的属性值,而我还没有在我的对象中创建属性noises

var animal = {};
animal.username = "Peggy";
animal["tagline"] = "Hello";
创建属性并将其添加到我的对象(&D)

var animal = {};
animal.username = "Peggy";
animal["tagline"] = "Hello";
这将创建以下内容:

animal {
      tagline: "Hello",
      username: "Peggy"
}
当我试图将其添加到对象中时,为什么以下操作不起作用

var noises = [];
animal[noises];
我在我的控制台中得到这个(同上):

我可以这样得到我的结果:

animal.noises = [];
这会将其输出到我的控制台:

animal {
  noises: [],
  tagline: "Hello",
  username: "Peggy"
}
但这仍然给我留下了一个问题:为什么不使用括号表示法呢?

使用

animal.noises = noises;


当你使用
动物[噪音]时这意味着当您试图从对象读取数据时。

对于
动物[噪音]

  • animal
    是对象
  • 噪音
    是对象的关键/属性
    动物
数组不能是键。如果您想在
动物
对象中放置
噪音
数组,可以按如下操作:

animal['noises'] = noises;

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

animal['noises']=noises
数组
[]
表示法用于获取需要在其周围加引号的对象的属性。数组符号通常用于获取包含特殊字符的对象的标识符。例如

   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'

.

动物[噪音]
表示您正试图访问
animal
的属性,其名称由
noises
给出。你没有在那里创建任何属性。我只是更新了问题。看看第三个代码block@CliffordFajardo这不会改变任何事情。你没料到动物会这么做
创建一个名为
tagline
的属性,其值为
Hello
,是吗?现在,为什么您希望
animal[[]]
(这实际上是您的尝试)创建一个名为
noises
的属性?您显然不知道括号表示法的含义,您应该在初学者JavaScript教程中查找它。谢谢。我也没能回忆起,用括号表示法时,我需要用“”来表示噪音。您的回答简洁明了。感谢您提供的精彩、简洁的示例!
   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'