简体   繁体   English

如何在Javascript中创建数组对象

[英]How to create object of array in Javascript

I want to create the object of list that looks like this: 我想创建看起来像这样的列表对象:

myObj = {"foo":[1,2,3,4], 
         "bar":[3,5,7,8]}

I tried this but failed 我尝试了这个但是失败了

var myObj = new Object();
myObj["foo"].push(1)
myObj["foo"].push(2)
#...etc

What's the right way to do it? 什么是正确的方法?

You need to create the array first 您需要先创建数组

myObj["foo"] = []

then call your push method 然后调用您的push方法

It depends, are you trying to reassign the myObj attribute foo with a completely new array ? 这取决于您是否要尝试使用全新array重新分配myObj属性foo Or are you trying to append to the already existing array ? 还是您要追加到已经存在的array

In the former case: 在前一种情况下:

myObj.foo = [1,5,6,4] // new array

And in the latter: 在后者中:

myObj.foo.concat(/*new numbers*/)

The {} notation is commonly used. {}表示法是常用的。

var myObj = {};
myObj.foo = [];
myObj.bar = [];

Later you can manipulate the arrays. 稍后您可以操纵数组。

myObj.bar.push('elem1');
myObj.bar.pop();
// ...

First you should declare the properties of the object as array in order not to get some unpleasent situations.So you can use new Object to create an object like this. 首先您应该将对象的属性声明为数组,以免出现一些不愉快的情况,因此您可以使用new Object来创建这样的对象。

var myObj=new Object;

and define properties as empty arrays 并将属性定义为空数组

myobj.prop1=[];
myObj.prop2=[];

then you can push whatever you want into prop1 or prop2 by simply reaching them inside the object as 那么您只需将它们伸入对象内部即可将所需的内容推入prop1或prop2

myObj.prop1.push(someData)

OR 要么

You can use a better way to declare this object like below 您可以使用更好的方法来声明此对象,如下所示

var myObj={
  prop1:[],
  prop2:[]
}

And again you can push whatever you like into them as i told above as myObj.prop1.push(data) 再一次,您可以按照我在上面作为myObj.prop1.push(data)的说明将任何您喜欢的内容推送到其中

Try first declare your object, so your second line goes first 尝试首先声明您的对象,所以第二行

var myObj = new Object();

then you fill your object with data 然后用数据填充对象

myObj = {"foo":[1,2,3,4],"bar":[3,5,7,8]}

then the rest of your code should work fine 那么其余的代码应该可以正常工作

myObj["foo"].push(1) myObj["foo"].push(2)

result [ 1, 2, 3, 4, 1, 2 ] 结果[ 1, 2, 3, 4, 1, 2 ]

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

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