2種檢查JavaScript數(shù)組是否為空的方法

Array.isArray(emptyArray) && emptyArray.length
例:
<html><head><meta charset="utf-8"><title>檢查數(shù)組是否為空或存在</title></head><body><b>檢查數(shù)組是否為空或存在</b><p>emptyArray = []</p><p>nonExistantArray = undefined</p><p>fineArray = [1, 2, 3, 4, 5]</p><p>單擊按鈕,檢查數(shù)組是否存在且不為空</p><button onclick="checkArray()">檢查數(shù)組</button><p>數(shù)組emptyArray是否為空或存在:<span></span></p><p>數(shù)組nonExistantArray是否為空或存在:<span></span></p><p>數(shù)組fineArray是否為空或存在:<span></span></p><script type="text/JavaScript">function checkArray() {let emptyArray = [];let nonExistantArray = undefined;let fineArray = [1, 2, 3, 4, 5];if(Array.isArray(emptyArray) && emptyArray.length)output = true;elseoutput = false;document.querySelector('.output-empty').textContent = output;if(Array.isArray(nonExistantArray) && nonExistantArray.length)output = true;elseoutput = false;document.querySelector('.output-non').textContent = output;if(Array.isArray(fineArray) && fineArray.length)output = true;elseoutput = false;document.querySelector('.output-ok').textContent = output;}</script></body></html>
方法二:使用typeof運算符和array.length
通過使用typeof運算符檢查數(shù)組的類型是否為“undefined”,數(shù)組是否為'null',來檢查數(shù)組是否存在。
通過使用array.length屬性,可以檢查數(shù)組是否為空;通過檢查返回的長度是否大于0,可以確保數(shù)組不為空。
然后,可以將這些屬性與(&&)運算符一起使用,以確定數(shù)組是否存在且不為空。
例:
<html><head><meta charset="utf-8"><title>檢查數(shù)組是否為空或存在</title></head><body><b>檢查數(shù)組是否為空或存在</b><p>emptyArray = []</p><p>nonExistantArray = undefined</p><p>fineArray = [1, 2, 3, 4, 5]</p><p>單擊按鈕,檢查數(shù)組是否存在且不為空</p><button onclick="checkArray()">檢查數(shù)組</button><p>數(shù)組emptyArray是否為空或存在:<span></span></p><p>數(shù)組nonExistantArray是否為空或存在:<span></span></p><p>數(shù)組fineArray是否為空或存在:<span></span></p><script type="text/JavaScript">function checkArray() {let emptyArray = [];let nonExistantArray = undefined;let fineArray = [1, 2, 3, 4, 5];if (typeof emptyArray != "undefined"&& emptyArray != null&& emptyArray.length != null&& emptyArray.length > 0)output = true;elseoutput = false;document.querySelector('.output-empty').textContent= output;if (typeof nonExistantArray != "undefined"&& nonExistantArray != null&& nonExistantArray.length != null&& nonExistantArray.length > 0)output = true;elseoutput = false;document.querySelector('.output-non').textContent= output;if (typeof fineArray != "undefined"&& fineArray != null&& fineArray.length != null&& fineArray.length > 0)output = true;elseoutput = false;document.querySelector('.output-ok').textContent= output;}</script></body></html>
本文完~

評論
圖片
表情
