如何在 JavaScript 中检查数组是否为真数组?

javascriptobject oriented programmingfront end technology更新于 2025/4/7 7:08:17

在 javascript 中,数组不是真正的数组。它们是 javascript 对象。因此,当我们尝试使用 typeof() 运算符了解它们的类型时,显示的输出将是对象。

语法

typeof(operand);

参数- typeof() 运算符接受操作数并返回操作数的数据类型。

在下面的例子中,即使变量 'a' 是一个数组,typeof() 运算符也会将输出返回为对象,因为一般来说每个数组都是一个对象。

示例

<html>
<body>
<script>
   var a = [1,2,5,"hello"];
   document.write(typeof(a));
   var b = {};
   document.write("</br>");
   document.write(typeof(b));
</script>
</body>
</html>

输出

object
object

与 typeof() 运算符不同,Array.isArray() 检查传递的参数是否为数组。如果参数是数组,则输出 true ,否则输出 false 。

语法

Array.isArray(array);

在下面的示例中,数组"a"和对象"b"通过 Array.isArray() 方法传递。此方法仔细检查它们并分别显示 true  和 false  作为输出。

示例

<html>
<body>
<script>
   var a = [1,2,5,"hello"];
   var res1 = Array.isArray(a);
   document.write(res1);
   document.write("</br>");
   var b = {};
   var res2 = Array.isArray(b);
   document.write(res2);
</script>
</body>
</html>

输出

true
false

相关文章


有用资源