Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách kiểm tra object có phải array trong JavaScript

Nhiều cách kiểm tra object có phải array trong JS.

1. Array.isArray() (Khuyên dùng, ES5+)

Tất cả browser hiện đại hỗ trợ.

Ví dụ

console.log(Array.isArray(undefined)); // false
console.log(Array.isArray(null));      // false
console.log(Array.isArray(""));        // false
console.log(Array.isArray({}));        // false
console.log(Array.isArray([]));        // true
console.log(Array.isArray([1, "hello"])); // true
console.log(Array.isArray(new Array())); // true

Kết quả

false false false false true true true

2. Kiểm tra constructor

arr.constructor === Array. Không hoạt động với null/undefined (throw error).

Ví dụ

// Sẽ lỗi:
console.log(undefined.constructor === Array); // TypeError
console.log(null.constructor === Array);      // TypeError

// An toàn:
console.log("".constructor === Array);        // false
console.log({}.constructor === Array);        // false
console.log([].constructor === Array);        // true
console.log([1, "hello"].constructor === Array); // true
console.log(new Array().constructor === Array);  // true

Kết quả

false false true true true

3. Object.prototype.toString.call() (Polyfill cũ)

Object.prototype.toString.call(arr) === '[object Array]'

Tóm tắt: Array.isArray() chuẩn nhất, cross-frame/iframe cũng đúng (constructor check fail cross-frame).