[英]Check if array is not empty with length JavaScript
我console.log(arr)
它顯示[]
但我console.log(arr.length)
它顯示0
嗎? 這讓我感到困惑,所以檢查數組是否包含某些東西的最佳方法是什么?
您可以通過檢查length
屬性來檢查數組是否為空:
if (arr.length === 0) {
// arr is empty
}
或者,檢查它是否包含某些項目:
if (arr.length) {
// arr is not empty
}
console.log(arr)
將顯示[]
表示一個空數組。 這就是它的顯示方式,而length
屬性為0
表示數組中沒有項目。
這是一個數組:['1','2','3','4'],因此,如果數組為空,它將看起來像這樣:[]。 我會這樣:
if(arr && arr.length){ console.log('then the array is created and it has value'); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.