如何在 JavaScript 中檢查一個物件是否為陣列?
陣列是一種資料型別,可以儲存多個相同資料型別的元素。例如,如果一個數組宣告為整數資料型別,那麼它將儲存一個或多個整數資料型別的元素。
要檢查給定的物件或瞭解資料型別,我們可以在 JavaScript 中直接使用 typeof() 方法。
使用 typeof() 方法
typeof() 是一個函式,它給出給定物件的型別。typeof() 將返回一個字串,該字串是給定運算元的資料型別。運算元可以是物件、變數或函式。對於所有這些,它都會相應地返回型別。
語法
typeof() 的語法如下。
Typeof(operand) // operand can be a function, object or a variable.
現在,我們將繼續瞭解此方法的工作原理。
示例 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)
這裡的 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)
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP