TypeScript判斷對象類型的4種方式代碼
更新時間:2023年07月22日 11:08:54 作者:蒼穹之躍
這篇文章主要給大家介紹了關于TypeScript判斷對象類型的4種方式代碼,TypeScript能根據一些簡單的規(guī)則推斷(檢查)變量的類型,你可以通過實踐很快的了解它們,需要的朋友可以參考下
一、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){ //循環(huán)判斷對象的原型是否等于類型的原型,直到對象原型為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+)\]$/, '$1'); }
使用案例:
<!--src/App.vue--> <script setup lang="ts"> 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) { // 如果是<a>標簽我們就導向 百度翻譯 el. } } } </script> <template> <input v-focus/> <p/> <a v-focus rel="external nofollow" >百度一下,你就知道</a> </template>
總結
相關文章
原生js實現addClass,removeClass,hasClass方法
這篇文章主要介紹了原生js實現addClass,removeClass,hasClass方法和使用原生JS實現jQuery的addClass, removeClass, hasClass函數功能,需要的朋友可以參考下2016-04-04js實現把圖片的絕對路徑轉為base64字符串、blob對象再上傳
本文主要介紹了JavaScript把項目本地的圖片或者圖片的絕對路徑轉為base64字符串、blob對象再上傳的方法,具有一定的參考價值,需要的朋友一起來看下吧2016-12-12