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

时间:2016-01-18 05:37:18

标签: javascript arrays object

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 = [];

如何将这些物体放入卡座阵列?对不起,如果这是一个愚蠢的问题,我很难找到答案。

3 个答案:

答案 0 :(得分:1)

您有几个选项,如评论中所述。

1)使用对象实例化数组:

var deck = [twoClubs, threeClubs, fourClubs];

2)将对象添加到数组中:

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

3)你甚至可以实例化数组并同时声明对象:

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

从技术上讲,这是最有效的方式(警告:这取决于浏览器/实现)。

答案 1 :(得分:1)

有几种方法可以做到这一点。您可以使用存在的值初始化数组:

var deck = [twoClubs, threeClubs, fourClubs]

或者你可以动态地将它们添加到数组中:

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

或者您甚至可以指定数组中的位置:

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

或者你可以混合搭配其中任何一个:

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

答案 2 :(得分:0)

现在,您已使用其他答案中提到的任一方法在数组中添加了对象。

var deck = [twoClubs, threeClubs, fourClubs];

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

您可以使用

从数组中检索并删除最后对象
deck.pop(); // remove and return last object

或 您可以使用索引从特定位置检索对象

deck[1] // returns threeClubs