判斷是否爲數組
使用typeof
無法區別數組、對象、null
type | ans |
---|---|
Undefined | “undefined” |
Null | “object” |
Number | “number” |
String | “string” |
Boolean | “boolean” |
Symbol | “symbol” |
function | “function” |
其他對象 | “object” |
typeof NaN === 'number'
typeof Infinity === 'number';
使用instanceof
可以判斷某個構造函數的
prototype
所指向的對象是否在另一個要檢測的原型鏈上
object instanceof constructor
var a = [];
a instanceof Array; //true
* 目前的 ES 規範中,只能讀取對象的原型而不能改變它,但藉助於非標準的proto屬
性a.__proto__ = {}
可以更改,返回false
;
* 多個窗口產生多個全局環境,不同的全局環境擁有不同的全局對象,從而擁有不同的內
置類型構造函數;
使用constructor
consr a = [];
a.constructor === Array; // true function Array() {[native code]}
const a = new Array;
a.constructor === Array // true
a.constructor = object;
a.constructor === Array; //false
a instanceof Array // true
* 除了Number
、String
、Boolean
、Symbol
、Undefined
、Null
的基本數據類
型有隻讀的原生構造函數。對象的 constructor 屬性可被修改
使用object
的toString
方法判斷
每個繼承自
object
的對象都有toString
方法
const a = ['Hello', 'World'];
const o = {x: 'Hello', y: 'World'};
const s = "Hello World";
a.toString() // "Hello World"
o.toString() // "[object object]"
s.toString() // 'Hello World'
Object.prototype.toString.call(a) // "[object Array]"
Object.prototype.toString.call(o) // "[object object]"
Object.prototype.toString.call(s) // "[object String]"
* apply
同理
使用isArray
ES5
新增
Array.isArray([]); //true
Array.isArray([1]); //true
Array.isArray(new Array()); //true
Array.isArray(Array.prototype); //true
* Polyfill
(IE9+
)
if(!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
}
}
* 可檢測iframes