判斷資料型別 toString

2021-10-12 12:43:27 字數 2172 閱讀 2424

每個物件都有乙個tostring()方法,當該物件被表示為乙個文字值時,或者乙個物件以預期的字串方式引用時自動呼叫。

預設情況下,tostring()方法被每個object物件繼承,如果該方法沒有在自定義物件中被覆蓋,tostring()返回'[object type]',其中type是型別

const obj =

newobject()

;console.

log(obj.

tostring()

);// [object object]

當然,我們根據這點,可以通過tostring()來獲取每個物件的型別。

/**

* @name 示例

* @description tostring 檢測物件型別

*/const tostring = object.prototype.tostring;

console.

log(tostring.

call

(new

date))

;// [object date]

console.

log(tostring.

call

(new

string))

;// [object string]

console.

log(tostring.

call

(math));

// [object math]

console.

log(tostring.

call

('***x'))

;// [object string]

console.

log(tostring.

call

(123))

;// [object number]

console.

log(tostring.

call([

]));

// [object array]

console.

log(tostring.

call()

);// [object object]

console.

log(tostring.

call

(undefined));

// [object undefined]

console.

log(tostring.

call

(null))

;// [object null]

console.

log(

'------');

console.

log(tostring.

(new

date))

;// [object date]

console.

log(tostring.

(new

string))

;// [object string]

console.

log(tostring.

(math));

// [object math]

console.

log(tostring.

('***x'))

;// [object string]

console.

log(tostring.

(123))

;// [object number]

console.

log(tostring.([

]));

// [object array]

console.

log(tostring.()

);// [object object]

console.

log(tostring.

(undefined));

// [object undefined]

console.

log(tostring.

(null))

;// [object null]

判斷資料型別

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