2种检查JavaScript数组是否为空的方法

Array.isArray(emptyArray) && emptyArray.length
例:
<html><head><meta charset="utf-8"><title>检查数组是否为空或存在</title></head><body><b>检查数组是否为空或存在</b><p>emptyArray = []</p><p>nonExistantArray = undefined</p><p>fineArray = [1, 2, 3, 4, 5]</p><p>单击按钮,检查数组是否存在且不为空</p><button onclick="checkArray()">检查数组</button><p>数组emptyArray是否为空或存在:<span></span></p><p>数组nonExistantArray是否为空或存在:<span></span></p><p>数组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运算符检查数组的类型是否为“undefined”,数组是否为'null',来检查数组是否存在。
通过使用array.length属性,可以检查数组是否为空;通过检查返回的长度是否大于0,可以确保数组不为空。
然后,可以将这些属性与(&&)运算符一起使用,以确定数组是否存在且不为空。
例:
<html><head><meta charset="utf-8"><title>检查数组是否为空或存在</title></head><body><b>检查数组是否为空或存在</b><p>emptyArray = []</p><p>nonExistantArray = undefined</p><p>fineArray = [1, 2, 3, 4, 5]</p><p>单击按钮,检查数组是否存在且不为空</p><button onclick="checkArray()">检查数组</button><p>数组emptyArray是否为空或存在:<span></span></p><p>数组nonExistantArray是否为空或存在:<span></span></p><p>数组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>
本文完~

评论
