JS数组判断

判断是否为数组

使用typeof

无法区别数组、对象、null

typeans
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

* 除了NumberStringBooleanSymbolUndefinedNull的基本数据类
型有只读的原生构造函数。对象的 constructor 属性可被修改

使用objecttoString方法判断

每个继承自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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值