JavaScript--对象-检查一个对象是否是数组

时间:2022-11-24 18:55:55
 <!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
//鄙视题: 判断一个对象是否是数组,有几种办法:
var obj1={};//Object
var obj2=[1,2,3];//Array
var obj3=function(){};//Function
var obj4={}; obj4.__proto__=[];
//obj4认[]当爹
/*否定: typeof 无法区分数组和对象
console.log(typeof obj1);//object
console.log(typeof obj2);//object
console.log(typeof obj3);//function
*/
//1. isPrototypeOf 不但检查直接父对象,而且检查整个原型链
console.log(Array.prototype.isPrototypeOf(obj1));
console.log(Array.prototype.isPrototypeOf(obj2));
console.log(Array.prototype.isPrototypeOf(obj3));
console.log(Array.prototype.isPrototypeOf(obj4)); //2. constructor 也可检查整个原型链
console.log(obj1.constructor==Array);
console.log(obj2.constructor==Array);
console.log(obj3.constructor==Array);
console.log(obj4.constructor==Array); //3. instanceof 也可检查整个原型链
//判断一个对象是否是指定构造函数的实例
console.log(obj1 instanceof Array);
console.log(obj2 instanceof Array);
console.log(obj3 instanceof Array);
console.log(obj4 instanceof Array); /*4. 每个对象内部都有一个属性: class
记录了创建对象时使用的类型名
如何访问对象内部的class:
只能调用原生的toString方法
Object.prototype.toString();
"[object Object]"
对象 class
强行调用原生toString:
原生toString.call(替代this的对象)
call做2件事: 1. 执行函数;2. 替换this!
Object.prototype.toString()
this->Object.prototype
Object.prototype.toString.call(obj1)
this->obj1
->在执行时,相当于obj1.toString()*/ console.log(
Object.prototype.toString.call(obj1)
=="[object Array]");//原生的
console.log(
Object.prototype.toString.call(obj2)
=="[object Array]");
console.log(
Object.prototype.toString.call(obj3)
=="[object Array]");
console.log(
Object.prototype.toString.call(obj4)
=="[object Array]"); /*5. ES5: isArray*/
//如果浏览器不支持isArray方法
//就在?添加isArray方法
//参数: obj要检查的对象
//函数体:
//1. 强行调用原生toString方法输出obj的class属性//2. 如果返回的结果是"[object Array]"才返回true
//否则返回false document.write(Array.isArray(obj1)+"<br>");
document.write(Array.isArray(obj2)+"<br>");
document.write(Array.isArray(obj3)+"<br>");
document.write(Array.isArray(obj4)+"<br>");
</script>
</head>
<body> </body>
</html>