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 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 Array
; false
nếu không phải mảng.
Mô tả
Nếu giá trị là 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 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ú |
---|---|---|
ECMAScript 5.1 (ECMA-262) The definition of 'Array.isArray' in that specification. |
Standard | Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.8.5. |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.isArray' in that specification. |
Standard | |
ECMAScript (ECMA-262) The definition of 'Array.isArray' in that specification. |
Living Standard |
Trình duyệt hỗ trợ
BCD tables only load in the browser
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.