简体   繁体   English

JavaScript:如何将对象存储在数组中?

[英]JavaScript: How do you store objects in an array?

function CreateSuit(suit){
  this.suit = suit;
  this.vaule = i;
  this.name = name;
}

var twoClubs = new Card ('clubs', 2, 'two of clubs');
var threeClubs = new Card ('clubs', 3, 'three of clubs');
var fourClubs = new Card ('clubs', 4, 'four of clubs');

var deck = [];

How do I put these objects into the deck array? 如何将这些对象放入卡座数组中? Sorry if this is a dumb question I am having trouble finding an answer. 抱歉,如果这是一个愚蠢的问题,我找不到答案。

You have a few options, as mentioned in the comments. 如评论中所述,您有一些选择。

1) Instantiate the array with the objects: 1)用对象实例化数组:

var deck = [twoClubs, threeClubs, fourClubs];

2) Add the objects onto the array: 2)将对象添加到数组中:

var deck = [];
deck.push(twoClubs);
deck.push(threeClubs);
deck.push(fourClubs);

3) You could even instantiate the array and declare the objects at the same time: 3)您甚至可以实例化数组并同时声明对象:

var deck = [new Card ('clubs', 2, 'two of clubs'), new Card ('clubs', 3, 'three of clubs'), new Card ('clubs', 4, 'four of clubs')];

Technically, this is the most efficient way (caveat: this is browser/implementation dependent). 从技术上讲,这是最有效的方式(注意:这取决于浏览器/实现)。

There are a few ways to do this. 有几种方法可以做到这一点。 You can initialize the array with the values present: 您可以使用存在的值初始化数组:

var deck = [twoClubs, threeClubs, fourClubs]

Or you can add them to the array on the fly: 或者,您可以将它们动态添加到阵列中:

var deck = [];
deck.push(twoClubs);
deck.push(threeClubs);
deck.push(fourClubs);

Or you can even specify where in the array you want to put them: 或者甚至可以指定要在数组中放置它们的位置:

var deck = [];
deck[2] = threeClubs;
deck[0] = fourClubs;
deck[1] = twoClubs

Or you can mix and match any of these: 或者您可以混合搭配以下任何一种:

var deck = [threeClubs];
deck[1] = twoClubs;
deck.push(fourClubs);

Now once you have added object in array using either of methods mentioned in other answers. 现在,一旦您使用其他答案中提到的任何一种方法在数组中添加了对象。

var deck = [twoClubs, threeClubs, fourClubs];

or 要么

var deck = [];
deck.push(twoClubs);
deck.push(threeClubs);
deck.push(fourClubs);

you can retrieve and remove last object from array by using 您可以使用以下方法检索和删除数组中的最后一个对象

deck.pop(); // remove and return last object

or you can use indexes to retrieve object from specific location 或者您可以使用索引从特定位置检索对象

deck[1] // returns threeClubs

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

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