如何在 Javascript 中检查对象是否为数组?

javascriptobject oriented programmingprogramming

数组是一种可以存储多个类似数据类型元素的数据类型。例如,如果数组被声明为整数数据类型,则它将存储一个或多个整数数据类型的元素。

要检查给定的对象或了解数据类型,我们可以直接使用 JavaScript 中的 typeof() 方法。

使用 typeof() 方法

typeof() 是一个函数,它给出给定对象的类型。typeof() 将返回一个字符串,该字符串是给定操作数的数据类型。操作数可以是对象、变量或函数。对于所有这些,它会相应地返回类型。

语法

typeof() 的语法如下。

Typeof(operand) // 操作数可以是函数、对象或变量。

现在,我们将继续了解此方法的工作原理。

示例 1

此示例演示如何使用 typeof() 获取操作数的数据类型 −

function getType(){ str = "Abdul Rawoof" arr = [1,3,5,8] num = 90 set1 = ([1,265,890,22]) dict = {a:1,b:2} console.log("The input is: ",str," and the type is: ",typeof(str)) console.log("The input is: ",arr," and the type is: ",typeof(arr)) console.log("The input is: ",num," and the type is: ",typeof(num)) console.log("The input is: ",set1," and the type is: ",typeof(set1)) console.log("The input is: ",dict," and the type is: ",typeof(dict)) } getType()

但是,当使用 typeof() 函数时,如果它是一个数组,它不会返回"Array",而是返回"Object"。因此,为了解决这个问题,使用了其他方法。

使用 isArray()

isArray() 是一个函数,如果给定的输入是一个数组,它会返回"array"。它仅用于了解给定的输入是否为数组,而 typeof() 则提供给定输入的数据类型。

如果给定的输入是数组,则此函数返回"true",如果不是,则返回"false"。

语法

以下是 isArray() 方法的语法。

Array.isArray(object)

此处的对象是 isArray() 的参数,它可以是数组、字符串、集合、映射等。

示例 2

此示例演示了如何使用 isArray() 函数检查数组 -

<!DOCTYPE html> <html> <head> </head> <body> <p> checking given input isx array with isArray() function </p> <script> dict = {name: "John", age: 18}; arr = ["red", "green", "blue", "yellow"]; arr1 = [1, 2, 3, 4, 5]; null1 = null; document.write("Given input is "+ dict + " is an array :" + Array.isArray(dict) + "<br>"); document.write("Given input is "+ arr + " is an array :"+Array.isArray(arr) + "<br>"); document.write("Given input is "+ arr1 + " is an array :"+Array.isArray(arr1) + "<br>"); document.write("Given input is "+ null1 + " is an array :"+Array.isArray(null1)); </script> </body> </html>

使用构造函数

您可以使用 arr.constructor === Array 来确定对象是否为数组。但这并不适用于所有对象。

// This will fail: console.log(undefined.constructor === Array) // This will fail: console.log(null.constructor === Array) console.log("".constructor === Array) console.log({}.constructor === Array) console.log([].constructor === Array) console.log([1, "hello"].constructor === Array) console.log(new Array().constructor === Array)

相关文章