Javascript NodeJS 计算数组中有多少个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29092193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS Count how many objects in array?
提问by prk
How would I count how many objects there are inside an array?
我如何计算数组中有多少个对象?
The array looking like:
数组看起来像:
[ {id: 1}, {id: 2}, ...]
I assume I could use count() if it was PHP, but what about NodeJS/Javascript?
我假设如果是 PHP,我可以使用 count(),但是 NodeJS/Javascript 呢?
Edit:
编辑:


if (offer.items_to_receive.length > 0) {
console.log("items: " + offer.items_to_receive.length);
for(var i = 0; i < offer.items_to_receive.length; i++) {
usersInRound.push(offer.steamid_other);
}
}
logData('Accepted trade offer from ' + offer.steamid_other + '. (tradeofferid: ' + offer.tradeofferid + ')\nWorth ' + offer.items_to_receive.length + ' tickets. ');
How come it can read the "worth X tickets", but not the other part?
为什么它可以读取“价值X票”,而不能读取其他部分?
回答by Alexander T.
Use .length
用 .length
var data = [{
id: 1
}, {
id: 2
}];
console.log(data.length);
Update, in your edit I see that
更新,在您的编辑中我看到
offer.items_to_receiveis undefined, ensure that object offerhas property items_to_receive(should be array);
offer.items_to_receiveis undefined,确保对象offer有属性items_to_receive(应该是数组);
回答by Zuber Surya
list = //YOUR OBJECT DATA
count= Object.keys(list).length;
count= Object.keys(list).length;
Object.keys() gives the count of keys
That should give proper count
那应该给出适当的计数
回答by Sheharyar
I think your question should be How to get Array Size in Javascript?
我认为您的问题应该是如何在 Javascript 中获取数组大小?
Answer:Use the lengthmethod.
答:使用length方法。
Examples:
例子:
[1,2,3].length
// => 3
var a = { num: 1, obj: {}, arr: [{}, 3, "asd", {q: 3}, 1] }
a.arr.length
// => 5

