嗨,伙計們,我正在嘗試解決這個問題,但無法弄清楚如何將作為物件的 typeof 陣列與物件型別進行比較......基本上如何從我的最終計數中排除所有不是“真實”物件的東西,這個問題是:
此函式采用不同資料型別的陣列。它應該回傳陣列中物件數量的計數。
我的代碼應該更好地解釋我的意思:
function countTheObjects(arr) {
let howManyObj = 0;
arr.forEach(function (type) {
console.log(typeof type);
if (typeof type === "object" && type !== null) {
howManyObj ;
}
});
return howManyObj;
}
console.log(
countTheObjects([1, {}, [], null, null, "foo", 3, 4, 5, {}, {}, {}, "foo"])
);
最終計數是 5,但應該是 4。我嘗試在條件中添加
(typeof type === "object" && type !== null && type !== [])
但沒有結果。我試圖了解如何從計數中排除 []..
如果我 console.log(typeof []) 結果是物件。所以我認為我以錯誤的方式處理這個問題。
謝謝您的支持。
uj5u.com熱心網友回復:
您可以使用 Array.isArray() 進行檢查。
請參閱https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
if (typeof type === "object" && type !== null && !Array.isArray(type)) {
howManyObj ;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520879.html
下一篇:如何使用加載函式更新類屬性
