--- title: Array.isArray() slug: Web/JavaScript/Reference/Global_Objects/Array/isArray tags: - Array - ECMAScript 5 - JavaScript - Phương Thức - Tham khảo - polyfill translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray ---
{{JSRef}}

Array.isArray() là một phương thức để xác định liệu giá trị truyền vào có phải là một mảng kiểu {{jsxref("Array")}}.

Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar');   // false
Array.isArray(undefined);  // false

Cú pháp

Array.isArray(value)

Tham Số

value
Giá trị được kiểm tra.

Giá trị trả về

true nếu giá trị là kiểu mảng {{jsxref("Array")}}; false nếu không phải mảng.

Mô tả

Nếu giá trị là {{jsxref("Array")}}, trả về true, nếu không thì trả về false.

Xem bài viết “Determining with absolute accuracy whether or not a JavaScript object is an array” để có thêm chi tiết. Giả sử ta có một {{jsxref("TypedArray")}} instance, false sẽ luôn được trả về.

Ví dụ

// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype);

// all following calls return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });

instanceof vs isArray

Để kiểm tra kiểu Array, nên dùng Array.isArray hơn là instanceof bởi vì nó vẫn ra đúng khi giá trị kiểm tra được truyền qua iframes.

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]

// Correctly checking for Array
Array.isArray(arr);  // true
// Considered harmful, because doesn't work through iframes
arr instanceof Array; // false

Polyfill

Chạy mã dưới đây đầu tiên trước các mã khác sẽ tạo Array.isArray() nếu nó không có sẵn.

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

Đặc tả

Đặc tả Trạng thái Ghi chú
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}} {{Spec2('ES5.1')}} Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}} {{Spec2('ES6')}}  
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}} {{Spec2('ESDraft')}}  

Trình duyệt hỗ trợ

{{Compat("javascript.builtins.Array.isArray")}}

Xem thêm