JS型別判斷

2022-01-14 05:49:12 字數 2929 閱讀 6796

typeof 123;   //

number

typeof 'test'; //

string

typeof

true; //

boolean

typeof [1,2,3]; //

object

typeof ; //

object

typeof

function(); //

function

typeof undefined; //

undefined

typeof

null; //

object

typeof

new date(); //

object

typeof /^[a-za-z]$/; //

object

typeof

new error(); //

object

注意⚠️: typeof null為object,typeof function (){}為function.在使用 typeof 運算子時採用引用型別儲存值會出現乙個問題,無論引用的是什麼型別的物件,它都返回 「object」

instanceof 是用來判斷 a 是否為 b 的例項,表示式為:a instanceof b,如果 a 是 b 的例項,則返回 true,否則返回 false。 在這裡需要特別注意的是:instanceof 檢測的是原型

class person

}let p = new person('張三')

console.log(p

instanceof person) //

ture

注意⚠️:

1 instanceof number //

false

'str' instanceof string //

false

true

instanceof boolean //

false

new number(1) instanceof number //

true

new string('str') instanceof string //

true

new boolean(true) instanceof boolean //

true

constructor是原型物件的屬性,他指向建構函式。

new number(1).constructor === number //

true

new string(1).constructor === string //

true

true.constructor === boolean //

true

new function().constructor === function //

true

new date().constructor === data //

true

new error().constructor === error //

true

.constructor === array //

true

document.constructor === htmldocument //

true

window.constructor === window //

true

或者使用constructor.name

栗子

js型別判斷

typeoftypeof 返回值有七種可能 number,string,boolean,object,function,undefined,symbol 侷限性 對於array,null等特殊物件使用typeof一律返回object。numbers typeof 37 number typeof m...

js型別判斷

js型別判斷,有如下三種 1 typeof 2 instanceof 3 object.prototype.tostring.call 4 arg.proto contructor.name 以判斷陣列為例,有如下幾種方法 function isarray arg return arg instan...

判斷JS型別

一 js的型別 js的基本型別共有七種 bigint bigint是一種內建物件,是處symbol外的第二個內建型別 number string boolen symbol undefined null。複雜資料型別有物件 object 包括基本的物件 函式 function 陣列 array 和內...