資料型別
基本型別
String、Number、Boolean、Null、Undefined
參考型別
Object、Array、Function
判斷資料型別的方式
1. 使用 typeof
typeof 'test' // string
typeof 1880 // number
typeof true // boolean
typeof null // object
typeof undefined // undefined
typeof {} // object
typeof [] // object
typeof function() {} // function
缺點:判斷基本型別還是可以的,判斷參考型別作用就沒那么大了,無法校驗陣列、物件、Null
2. 使用 constructor
let xiaoming = 'text';
xiaoming.constructor // String(){}
let xiaoming = 1880;
xiaoming.constructor // Number(){}
let xiaoming = true;
xiaoming.constructor // Boolean(){}
let xiaoming = null;
xiaoming.constructor // 報錯
let xiaoming = undefined;
xiaoming.constructor // 報錯
let xiaoming = {};
xiaoming.constructor // Object(){}
let xiaoming = [];
xiaoming.constructor // Array(){}
let xiaoming = function() {};
xiaoming.constructor // Function(){}
缺點:無法校驗 Null 和 Undefined
3. 使用 instanceof
function A() {}
function A1() {}
function B() {}
A1.prototype = new A(); // A1 繼承 A
let xiaoming = new A1(); // 實體化
console.log(xiaoming instanceof A); // true
console.log(xiaoming instanceof A1); // true
console.log(xiaoming instanceof B); // false
缺點:只適用于判斷物件屬于什么型別,其他的都不太適用
4. 使用 Object.prototype.toString.call()
Object.prototype.toString.call('text'); // [object String]
Object.prototype.toString.call(1880); // [object Number]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call(function() {}); // [object Function]
目前比較準確的一種方式
文章的內容/靈感都從下方內容中借鑒
-
【持續維護/更新 500+前端面試題/筆記】https://github.com/noxussj/Interview-Questions/issues
-
【大資料可視化圖表插件】https://www.npmjs.com/package/ns-echarts
-
【利用 THREE.JS 實作 3D 城市建模(珠海市)】https://3d.noxussj.top/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/297037.html
標籤:其他
