JavaScript Array isArray()

isArray() 方法用于检查传入的参数是否是数组

示例

let numbers = [1, 2, 3, 4];

// checking whether numbers is an array or not console.log(Array.isArray(numbers));
let text = "JavaScript";
// checking whether text is an array or not console.log(Array.isArray(text));
// Output: // true // false

isArray() 语法

isArray() 方法的语法是

Array.isArray(value)

isArray() 方法是一个静态方法,通过 Array 类名进行调用。


isArray() 参数

isArray() 方法接受一个单个参数

  • value - 要检查的值。

isArray() 返回值

isArray() 方法返回

  • true 如果传入的值是 Array
  • false 如果传入的值不是 Array

注意:此方法对于 TypedArray 实例始终返回 false。


示例 1:使用 isArray() 方法

let fruits = ["Apple", "Grapes", "Banana"];

// checking whether fruits is an array or not console.log(Array.isArray(fruits));
let text = "Apple";
// checking whether text is an array or not console.log(Array.isArray(text));

输出

true
false

在上面的示例中,我们使用 isArray() 方法来找出 fruitstext 是否是数组。

(Array.isArray(fruits)) 返回 true,因为 fruits 是一个数组对象,而 (Array.isArray(text)) 返回 false,因为 text 不是数组(它是一个字符串)。


示例 2:isArray() 检查其他数据类型

// passing an empty array [] console.log(Array.isArray([])); // true
// we have created an array with element 7 and // passed that value to isArray() console.log(Array.isArray(new Array(7))); // true
// passing a boolean value console.log(Array.isArray(true)); // false // passing undefined console.log(Array.isArray(undefined)); // false // not passing any argument in isArray() console.log(Array.isArray()); // false

输出

true
true
false
false
false

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战