1. 判断一个对象是不是数组类型,一共有六种方法,分别是:
(1) Array.prototype.isPrototypeOf(arr) // 返回布尔值
作用:检测括号中的值是否具有数组的原型 Array.prototype
(2) arr instanceof Array // 返回布尔值
作用:前者arr是不是构造函数Array构造出来的
(3) Object.getPrototypeOf(arr) === Array.prototype // 返回布尔值
作用: Object.getPrototypeOf()返回括号中arr的原型是不是 Array.prototype
(4) Object.prototype.toString.call(arr) === “[object Array]”
作用:判断arr属于的内置类型是否是"[object Array]"this指向问题: ① 谁调用toString方法,this就指向谁
② 用call改变this的指向,让this指向括号中的arr
(5) Array.isArray(arr) // 返回布尔值
作用:用于确定括号中的arr是否是一个数组
(6) arr.constructor === Array // 返回布尔值
作用: 判断arr的构造函数是否是Array
附赠
2. 编写type函数,扩展typeof操作符的不足,实现更精细的类型扩展
function type(x
) {
if (typeof (x
) == 'object') {
if (x
== null) {
return null;
} else if (Object
.prototype
.toString
.call(x
) == "[object Array]") {
return 'array';
} else if (Object
.prototype
.toString
.call(x
) == "[object Number]" && typeof (x
) == 'object') {
return "[object Number]";
} else if (Object
.prototype
.toString
.call(x
) == "[object String]" && typeof (x
) == 'object') {
return "[object String]";
} else if (Object
.prototype
.toString
.call(x
) == "[object Boolean]" && typeof (x
) == 'object') {
return "[object Boolean]";
} else {
return 'object';
}
} else {
if (x
+ "" == 'NaN') {
return NaN;
} else {
return typeof (x
);
}
}
}
2020—10—4 js基础知识 by code_he