对象的长度未定义

时间:2018-02-21 01:42:20

标签: javascript arrays object

我有一个对象,我试图获得长度(看看里面有多少个对象)。创建对象的代码如下:

 var threeDSCards = [];
 var card = {}

card[0] = {cardid: 10127, cardnumber: 411111111111, expMonth: 02, expYear: 18};                    
card[1] = {cardid: 10128, cardnumber: 411111111111, expMonth: 01, expYear: 19};

threeDSCards.push(card);

代码在控制台中为对象输出:

[{
"0":{"cardid":10127,"cardnumber":411111111111,"expMonth":2,"expYear":18},
"1":{"cardid":10128,"cardnumber":411111111111,"expMonth":1,"expYear":19}
}]

我期待长度为2,因为对象中存储了2张卡

2 个答案:

答案 0 :(得分:2)

如果您正在执行上述操作,它将创建一对键值对象,如果您只需要普通对象,则只需创建新变量并将它们推送到数组

<强>样本

&#13;
&#13;
 var threeDSCards = [];
 var card = {}

var card1 = {cardid: 10127, cardnumber: 411111111111, expMonth: 02, expYear: 18};                    
var card2 = {cardid: 10128, cardnumber: 411111111111, expMonth: 01, expYear: 19};

threeDSCards.push(card1);
threeDSCards.push(card2);
console.log(threeDSCards.length);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用Object.keys(yourObject).length来获取对象拥有的键(属性)数量。