js中判斷數據類型的幾種方式?

你好,那我們開始吧,請做一個簡單的自我介紹。然後就是巴拉巴拉,我的名字就不用說了哈,在那畢業,什麼學歷,什麼時候開始從事,在哪家公司,技術全棧是什麼,做過什麼項目。其實這些東西簡歷上都有,但形式還得走,形式雖然不好,但卻很好看不是吧。
那好,我們開始進行技術面試,首先你說下js中判斷數據類型的幾種方式?
小趙童鞋說出了三個?有一個instanceof 忘記了
1.typeof 脫口而出 而且這個用的也比較多?說實話工作中 常用地你確實會銘記 但不常用的 還真的會忘記,就像是框架 技術這些東西 常用你就容易記住 不常用就容易忘記

var a="hello";
var b=[];
var c=undefined;
var d=null;
var e={};
var f=function(){};
var g=12;
console.log(typeof a);
console.log(typeof b);
console.log(typeof c);
console.log(typeof d);
console.log(typeof e);
console.log(typeof f);
console.log(typeof g);
// 上面輸出
string
object
undefined
object
object
function
number

從上面可以看出來 能判斷出來 string undefined function number 等數據類型
數組 對象形式 好像只能判斷出來一個 object

  1. constructor 博主說出來這個 通過構造函數進行判斷
var a="hello";
var b=[];
var e={};
var f=function(){};
var g=12;
console.log(a.constructor);
console.log(b.constructor);
console.log(e.constructor);
console.log(f.constructor);
console.log(g.constructor);
console.log(a.constructor==String);
console.log(b.constructor==Array);
console.log(e.constructor==Object);
console.log(f.constructor==Function);
console.log(g.constructor==Number);

上面的輸出結果是: 可以使用
[Function: String]
[Function: Array]
[Function: Object]
[Function: Function]
[Function: Number]
true
true
true
true
true
3.第三種最穩了 相當於從源頭進行判斷了 (完美解決問題)

var a="hello";
var b=[];
var e={};
var f=function(){};
var g=12;
console.log(Object.prototype.toString.call(a));
console.log(Object.prototype.toString.call(b));
console.log(Object.prototype.toString.call(e));
console.log(Object.prototype.toString.call(f));
console.log(Object.prototype.toString.call(g));
console.log(Object.prototype.toString.call(a)=="[object String]");
console.log(Object.prototype.toString.call(b)=="[object Array]");
console.log(Object.prototype.toString.call(e)=="[object Object]");
console.log(Object.prototype.toString.call(f)=="[object Function]");
console.log(Object.prototype.toString.call(g)=="[object Number]");

[object String]
[object Array]
[object Object]
[object Function]
[object Number]
true
true
true

4.最後一種也是 筆者忽然忘記的一種 instanceof
判斷對象是否屬於後面對象的實例
先舉一個小demo

function Person(){
	this.name="zhangsan";
}
var a=new Person();
console.log(a instanceof Person); // true
var b=3;
console.log(b instanceof Person); //false

這樣方法就來了

var a=[];
var b={};
var c=function(){};
console.log(a instanceof Array);  // true
console.log(b instanceof Object); // true
console.log(c instanceof Function); // true

上面我都驗證了true的情況 其實 false的情況 把前面的驗證對象更換成其他的就可以了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章