Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

判断数组的方式有哪些【热度: 509】 #431

Open
yanlele opened this issue Jun 8, 2023 · 1 comment
Open

判断数组的方式有哪些【热度: 509】 #431

yanlele opened this issue Jun 8, 2023 · 1 comment
Labels
JavaScript JavaScript 语法部分 网易 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Jun 8, 2023

关键词:js判断数组方法

在 JavaScript 中,判断一个值是否为数组有多种方式,以下是几种常见的方法:

  1. Array.isArray(): 使用 Array.isArray() 方法可以判断一个值是否为数组。它是 ES5 中新增的方法,返回一个布尔值。
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true

const obj = { a: 1, b: 2 };
console.log(Array.isArray(obj)); // false
  1. instanceof 操作符:可以使用 instanceof 操作符检查一个对象是否是特定类的实例。对于数组,可以使用 instanceof Array 判断。
const arr = [1, 2, 3];
console.log(arr instanceof Array); // true

const obj = { a: 1, b: 2 };
console.log(obj instanceof Array); // false
  1. Array.prototype.isArray():可以通过 Array.prototype.isArray.call() 方法来判断一个值是否为数组。这种方式在某些特定情况下使用较多。
const arr = [1, 2, 3];
console.log(Array.prototype.isArray.call(arr)); // true

const obj = { a: 1, b: 2 };
console.log(Array.prototype.isArray.call(obj)); // false
  1. Object.prototype.toString():可以使用 Object.prototype.toString.call() 方法来获取一个值的类型信息,进而判断是否为数组。返回的结果是一个包含类型信息的字符串,例如 "[object Array]"。
const arr = [1, 2, 3];
console.log(Object.prototype.toString.call(arr) === "[object Array]"); // true

const obj = { a: 1, b: 2 };
console.log(Object.prototype.toString.call(obj) === "[object Array]"); // false

这些方法各有特点,根据实际需求选择合适的方法进行判断。通常推荐使用 Array.isArray() 方法来判断一个值是否为数组,因为它是专门用于判断数组的标准方法,并且在大多数现代浏览器中得到广泛支持。

@yanlele yanlele added JavaScript JavaScript 语法部分 网易 公司标签 labels Jun 8, 2023
@yanlele yanlele modified the milestones: , Jun 8, 2023
@Long-34
Copy link

Long-34 commented Jun 26, 2024

Array.prototype.isPrototypeOf([]);

Object.getPrototypeOf([]) === Array.prototype

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript 语法部分 网易 公司标签
Projects
None yet
Development

No branches or pull requests

2 participants