总结:判断对象是否为数组的方法
1、Object.prototype.toString.call() (所有类型都可以用来判断)
Object.prototype.toString.call({})
2、instanceof方法 (判断Array.prototype是否在该对象的原型链__proto__中)
console.log([] instanceof Array); //true
3、constructor方法 (判断该对象的构造函数是否是Array)
console.log([].constructor === Array); // true
4、Array.isArray() (数组自带的判断方法)
console.log(Array.isArray([])); // true
JavaScript中检测对象的方法
1.Object.prototype.toString.call() (推荐!!!)
Object.prototype.toString的行为:首先,取得对象的一个内部属性,然后依据这个属性,统一返回格式“[object Xxx]"的字符串作为结果. 利用这 个方法,再配合call,我们可以取得任何对象的内部属性,然后把类型检测转化为字符串比较,以达到我们的目的。
function getType(obj){
let type = Object.prototype.toString.call(obj).slice(8,-1);
// 特殊情况,单独处理 ---- 在type为Number时,原数据obj可能是Number,也可能是NaN
if(type === 'Number' && isNaN(obj)){
return "NaN"
}else{
return type
}
}
用法如下
getType('123') // "String"
getType(100) //"Number"
getType(true) //"Boolean"
getType(undefined) // "Undefined" getType() // "Undefined"
getType(Symbol()) //"Symbol"
getType(null) // "Null"首字母大写
getType(NaN) // "NaN"
getType([]) // "Array"
getType({}) // "Object"
getType(console.log) // "function"
getType(/123/g) //"RegExp"
getType(new Date()) //"Date"
getType(window) // "Window"
2. instanceof操作符 (可用于检测是否是数组)
instanceof运算符用于检测构造函数的prototype属性是否出现在 **某个实例对象** 的原型链上
[] instanceof Array //true
{} instanceof Array //false
{} instanceof Object //true
[] instanceof Object //true
let a = ''
a instanceof String //false 由于a并不是一个实例对象,它是一个字面量变量
let b = new String('xxx')
b instanceof String //true
所有对象类型 instanceof Object 都是 true
3.对象的constructor属性 (可用于检测是否是[ ]和{ })
所有对象都会从它的原型上继承一个 constructor 属性:
console.log({}.constructor === Object); // true
console.log({}.constructor === Array); //false
console.log([].constructor === Array); // true
console.log([].constructor === Object); //false
4. typeof操作符 ()
typeof 操作符返回一个字符串
利用typeof判断类型,只会返回
'string'、'number'、'undefined'、 'boolean'、'function'、'symbol'、'object' 七类
利用typeof判断为object,不一定就是 {},也有可能是 [ ], null,正则,日期对象
typeof 'abc' // 'string'
typeof 98 // 'number'
typeof age // 'undefined'
typeof true // 'boolean'
typeof console.log // 'function'
typeof Symbol() // 'symbol'
typeof null // 'object'
typeof {} //'object'
typeof [] //'object'
如果我们想要判断一个变量是否存在,可以使用typeof (不能使用if(a), 若a未声明,则报错)
5.Array.isArray() (推荐)
检测一个值是否为数组。IE9+、 Firefox 4+、Safari 5+、Opera 10.5+和Chrome都实现了这个方法。但是在IE8之前的版本是不支持的
console.log(Array.isArray([])); //true
兼容浏览器写法
var arr = [1,2,3,1];
var arr2 = [{ abac : 1, abc : 2 }];
function isArrayFn(value){
if (typeof Array.isArray === "function") {
return Array.isArray(value);
}else{
return Object.prototype.toString.call(value) === "[object Array]";
}
}
alert(isArrayFn(arr));// true
alert(isArrayFn(arr2));// true
6.typeof与instanceof都是判断数据类型的方法,区别如下:
-
返回值
:typeof会返回一个变量的基本类型,instanceof返回的是一个布尔值 -
instanceof
:instanceof 可以准确地判断复杂引用数据类型,但是不能正确判断基础数据类型 -
typeof
:typeof 也存在弊端,它虽然可以判断基础数据类型(null 除外),但是引用数据类型中,除了function 类型以外,其他的也无法判断
参考链接 https://www.cnblogs.com/heshan1992/p/6927690.html