简体   繁体   English

如何将对象构造函数添加到另一个对象内的空数组中

[英]How to add an object constructor into an empty array that is within another object

How do arrays within an object receive data from another object, and will creating an array value of a property still make that property an object? 一个对象内的数组如何从另一个对象接收数据,并且创建属性的数组值仍会使该属性成为对象? (Confusing) (令人困惑)

For example, 例如,

function example(red, blue){
    this.red1 = red;
    this.blue1 = blue;
}
var colors = new example("Red", "Blue");

//Object 2, 
var colorShapes = {triangle: blue, square: []};

//My attempt
var array1 = colorShapes.square.push(colors);
console.log(array1);

You can manipulate arrays within objects (or objects within arrays, or any mix thereof) the same way you would manipulate an object or an array normally. 您可以像正常操作对象或数组一样操作对象内的数组(或数组内的对象,或其任何组合)。 You only need to be able to reference it. 您只需要能够引用它。

So in your example, colorShapes.square evaluates to an array, and that array can be manipulated in the same way that any array could be manipulated. 因此,在您的示例中, colorShapes.square求值为一个数组,并且该数组的操作方式与任何数组的操作方式相同。

Your question is a little confusing, so please feel free to ask any clarifying questions. 您的问题有点令人困惑,因此请随时提出任何澄清的问题。

First, in colorShapes it should be triangle: "blue" 首先,在colorShapes中,它应该是triangle: "blue"

Second, push returns the length of the array. 第二,推返回数组的长度。 You want to just run colorShapes.square.push(colors) 您只想运行colorShapes.square.push(colors)

Now colorShapes.square[0] evaluates to your object colors 现在colorShapes.square [0]会评估为您的对象colors

Are you familiar with the chrome console? 您熟悉Chrome控制台吗? Here is a screenshot of the code we execute, and the structure afterwards: 这是我们执行的代码的屏幕截图,以及之后的结构:

Chrome控制台截图

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

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