判断数组的方法

135 阅读2分钟

使用Object.prototype上的原生toString方法来判断数据类型:

(1) Object.prototype.toString.call(value)

每一个继承Object的对象都有tostring方法,如果tostring方法没有重写的话,会返回[Object type],其中type为对象的类型。当然除了Object类型的对象外,其他类型使用toString方法,会返回内容的字符串,所以需要使用call或apply来改变toString方法的执行上下文。

const an = ["hello", "world"];
console.log(an.toString()); // hello,world
console.log(Object.prototype.toString.call(an)); // [object Array]

该方法对于所有的基本数据类型都能判断,包括undefined 、null。但不能区分自定义对象类型,自定义对象类型可以采用instanceof区分。

1、判断基本数据类型
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(123) // [object Number]
Object.prototype.toString.call(true) // [object Boolean]

2、判断原生引用类型
函数类型
function fn(){console.log('test')}
Object.prototype.toString.call(fn) // [object Function]
数组类型
var arr = [1, 2, 3];
Object.prototype.toString.call(arr) // [object Array]
正则表达式
var reg = /[hbc]at/gi;
Object.prototype.toString.call(reg); // [object RegExp]
自定义类型

function Person(name, age) {
this.name = name;
this.age = age;
}

var person = new Person("rose", 18);
Object.prototype.toString.call(person); // [object Object]
很显然,这种方法判断person是否是Person的实例是不准确的,只能用instanceof操作符来判断。如下:
console.log(person instanceof Person); // true

3、判断原生JSON对象: var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON)
console.log(isNativeJSON); // 输出结果为 [object JSON] 说明JSON是原生的,否则不是

(2)instanceof

自定义对象可以采用instanceof来判断对象类型。
instanceof的内部机制是通过判断对象的原型链上是否能找到类型的prototype.
使用instanceof判断一个对象是否是数组,isntanceof会判断这个对象的原型上是否能找到对应的Array 的原型,找到为true,否则为false。
const arr=[1,2,3]
console.log(arr instanceof Array); // true

但instanceof只能用来判断对象类型,原始类型不可以。并且所有对象类型 instanceof Object都是true。
console.log("a" instanceof String); // false
console.log(true instanceof Boolean); // false

(3)Array.isArray()

  • 功能:同来判断是否是数组
  • instanceof 与 isArray

当检测Array实例时,Array.isArray优于instanceod,因为Array.isArray可以检测出iframes ,instanceof不可以
var iframe = document.createElement('iframe')
document.body.appendChild(iframe)
xArray = window.frames[window.frames.length - 1].Array
// console.log(xArray); // ƒ Array() { [native code] }
var arr = new xArray(1, 2, 3)

// console.log(Array.isArray(arr)); // true
// console.log(Object.prototype.toString.call(arr)); //[object Array]
console.log(arr instanceof Array); // false

(4) tpeof

只能用来判断基本数据类型,包括string 、number、boolean、undefined、symbol。对于数组、对象或null,用typeof判断的结果都是Object,无法检测出具体的引用类型。

ending~