判斷資料型別

2022-02-18 21:38:51 字數 766 閱讀 6138

1、typeof:只能判斷基本資料型別,不能判斷引用資料型別----判斷出來的都是object

string、number、boolean、undefined、object、function、symbol

2、instanceof:判斷乙個物件是否是乙個類的例項

只能進行型別的對比,不能進行型別的判斷

3、object.prototype.tostring.call():準確的判斷出資料的型別

----[object number]----型別的首字母大寫

function

istype(data, type)

let name = object.prototype.tostring.call(data) //

借用object.prototype.tostring()獲取資料型別

let typename = typeobj[name] || '未知型別' //

匹配資料型別

return typename === type //

判斷該資料型別是否為傳入的型別

}console.log(

istype({}, 'object'), //

true

istype(, 'array'), //

true

istype(new date(), 'object'), //

false

istype(new date(), 'date'), //

true

)

判斷資料型別

typeof 如果使用typeof來判斷資料型別的話,結果如下 var num new number 123 var str new string 1223 var bool new boolean false console.log typeof 123,number typeof num,obj...

判斷資料型別

typeof 判斷基本資料型別 不能區分null object 弊端不能區分 陣列 物件 和 null console.log typeof dddd console.log typeof 12 console.log typeof true console.log typeof undefined...

資料型別判斷

可以判斷基本資料型別,它返回的資料型別的字串 返回結果只能包括number,boolean,string,function,object,undefined 但不能判斷null array,可以使用typeof判斷變數是否存在 如if typeof a undefined 但是對於一些建立的物件,它...