美文网首页
21,js如何判断类型

21,js如何判断类型

作者: r8HZGEmq | 来源:发表于2019-11-19 17:45 被阅读0次

1,Object.prototype.toString.call(xxx);
因为每个Object都有toString方法,但是除了Object类型外,其他直接toString会返回内容字符串。
所以我们通过call或者apply改变toString的执行上下文

const an = ['Hello','An'];
an.toString(); // "Hello,An"
Object.prototype.toString.call(an); // "[object Array]"
// 常用在,判断“浏览器内置”的对象
Object.prototype.toString.call('An') // "[object String]"
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call(Symbol(1)) // "[object Symbol]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(function(){}) // "[object Function]"
Object.prototype.toString.call({name: 'An'}) // "[object Object]"

2,instanceof
原理是:判断对象原型链能不能找到类型的prototype

// 会判断[ ]的原型链是否会找到Array的原型
[]  instanceof Array; // true
但是:// instanceof只能来判断对象类型,且所有对象类型,都属于Object
[]  instanceof Object; // true

3,

Array.isArray([])
true
Array.isArray("11")
false
// Array.isArray是ES5才新增的方法,不存在的时候可以用Object.prototype
if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

4,call知识点补充

console.log("call")
1,call 是 Function 对象自带的一个方法
2,可以改变函数体内部的 this 指向,第一个参数就是 this要指向的对象,也就是想指定的上下文,|
3,后面的参数它会按顺序传递进去。它的函数会被立即调用。

相关文章

网友评论

      本文标题:21,js如何判断类型

      本文链接:https://www.haomeiwen.com/subject/ifrgictx.html