[英]How to count the objects in javascript?
我有一個函數,它包含許多數據類型的數組。
function count(totalObjs) {
var count=0;
for(var i=0; i<=arr.length; i++) {
count ++;
}
return count;
}
要僅對數組中的對象進行計數, 不能執行以下操作:
typeof x == "object"
因為這對於一個對象,數組或null
返回true
。
最好檢查toString
它會返回[object Object]
中的對象。
const arr = [1,{},[],null,null,'foo',3,4,5,{},{},{},'foo']; const count = arrObj => arrObj.filter(e => e && e.toString() == "[object Object]").length; console.log(count(arr));
如果希望在不創建幾乎未使用的中間數組的情況下計算出現次數,可以使用reduce
:
const count = arr => arr.reduce((a, item) => a + (item && item.constructor === Object), 0); console.log(count([1, [], null, 3, 4, 5, {}, {}, {}, 'foo']));
不太典型,只需要提取其中包含鍵的對象就可以了
Taking an array having null, array, blank object and string and object having value in it.
var arr = [1, [], null, 3, 4, 5, {key: 'val'}, {}, {}, 'foo']
const result = arr.filter(val => (val instanceof Object && Object.keys(val).length > 0));
Now get the count of objects having values in it.
console.log('result', result.length);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.