TypeScript判断对象类型的四种方式

02-27 1314阅读 0评论

一、typeof

typeof "";  //string
typeof 1;   //number
typeof false; //boolean
typeof undefined; //undefined
typeof function(){}; //function
typeof {}; //object
typeof Symbol(); //symbol
typeof null; //object
typeof []; //object
typeof new Date(); //object
typeof new RegExp(); //object

二、instanceof

{} instanceof Object; //true
[] instanceof Array;  //true
[] instanceof Object; //true
"123" instanceof String; //falsenew String(123) instanceof String; //true

三、constructor

function instance(left,right){
    let prototype = right.prototype;  //获取类型的原型
    let proto = left.__proto__;       //获取对象的原型
    while(true){    //循环判断对象的原型是否等于类型的原型,直到对象原型为null,因为原型链最终为null
       if (proto === null || proto === undefined){
           return false;
       }
       if (proto === prototype){
           return true;
       }
       proto = proto.__proto__;
     }
}
console.log(instance({},Object)); //true
console.log(instance([],Number)); //false

四、Object.prototype.toString()

function getType(obj){
  let type  = typeof obj;
  if(type != "object"){
    return type;
  }
  return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '');
}

使用案例:

TypeScript判断对象类型的四种方式,TypeScript判断对象类型的四种方式,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,我们,百度,第1张
(图片来源网络,侵删)

const vFocus = {
  mounted: (el: HTMLElement, binding: any) => {
    // 指令绑定的元素
    console.log(typeof el);
    console.log(el);
    // 指令绑定的参数
    console.log(binding)
    // 如果是输入框
    if (el instanceof HTMLInputElement) {
      // 元素聚焦
      el.focus();
      el.placeholder = '请输入';
      el.value = '勤奋、努力'
    }else if (el instanceof HTMLAnchorElement) {
      // 如果是标签我们就导向 百度翻译
      el.href='https://fanyi.baidu.com/'
    }
  }
}


  
  

百度一下,你就知道

TypeScript判断对象类型的四种方式

 

TypeScript判断对象类型的四种方式,TypeScript判断对象类型的四种方式,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,我们,百度,第3张
(图片来源网络,侵删)
TypeScript判断对象类型的四种方式,TypeScript判断对象类型的四种方式,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,我们,百度,第4张
(图片来源网络,侵删)

免责声明
本网站所收集的部分公开资料来源于AI生成和互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复: 表情:
评论列表 (暂无评论,1314人围观)

还没有评论,来说两句吧...

目录[+]