判斷資料型別

2022-07-11 08:06:12 字數 1455 閱讀 8385

object.prototype.tostring.call(123).slice(8, -1) //

number

//直接輸出數型別 首字母大寫 number、array、function等

下面是各種資料型別呼叫tostring()方法的返回值

資料型別

例子return

字串「foo」.tostring()

「foo」

數字1.tostring()

uncaught syntaxerror: invalid or unexpected token

布林值false.tostring()

「false」

undefined

undefined.tostring()

uncaught typeerror: cannot read property 『tostring』 of undefined

null

null.tostring()

uncaught typeerror: cannot read property 『tostring』 of null

string

string.tostring()

「function string() 」

number

number.tostring()

「function number() 」

boolean

boolean.tostring()

「function boolean() 」

array

array.tostring()

「function array() 」

function

function.tostring()

「function function() 」

date

date.tostring()

「function date() 」

regexp

regexp.tostring()

「function regexp() 」

error

error.tostring()

「function error() 」

promise

promise.tostring()

「function promise() 」

obejct

object.tostring()

「function object() 」

math

math.tostring()

「[object math]」

所有類在繼承object的時候,改寫了tostring()方法。 object原型上的方法是可以輸出資料型別的。因此我們想判斷資料型別時,也只能使用原始方法。

繼而可使用這個方法去判斷資料型別:

object.prototype.tostring.call(obj)

判斷資料型別

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 但是對於一些建立的物件,它...