1. 程式人生 > >js 驗證數據類型的4中方法

js 驗證數據類型的4中方法

string obj image 並且 操作 .html jet 操作數 boolean

1.typeof 可以檢驗基本數據類型 但是引用數據類型(復雜數據類型)無用;

技術分享圖片

總結 : typeof 無法識別引用數據類型 包括 bull;

2.instanceof是一個二元運算符,左操作數是一個對象,右操作數是一個構造函數。如果左側的對象是右側構造函數的實例對象,則表達式返回true;否則返回false

  如果左操作數不是對象,返回false,如果右操作數不是函數,則拋出一個類型錯誤異常TypeError

console.log( true instanceof Boolean) // boolean
console.log( "string" instanceof String) // string

console.log( 123 instanceof Number) // number
// console.log( undefined instanceof ) //語法錯誤
console.log( function(){} instanceof Function) //function
// console.log( null instanceof null) //語法錯誤
console.log( [1,2,3] instanceof Array) //objet
console.log( {"name":"liming"} instanceof Object ) // object

總結 :null 和 undefined 沒有構造函數 使用此方法會報錯!!! 無法鑒別基本數據類型 並且引用數據類型全部為對象 !!!

3.constructor

  實例對象的constructor屬性指向其構造函數。如果是對象類型,則輸出function 數據類型(){}; null undefiend 報錯

技術分享圖片

4.Object.prototype.toString()方法

  對象的類屬性是一個字符串,用以表示對象的類型信息。javascript沒有提供設置這個屬性的方法,但有一種間接方法可以查詢它

  Object.prototype.toString()方法返回了如下格式的字符串:[object 數據類型]

console.log(Object.prototype.toString.call("string"));//[object String]
console.log(Object.prototype.toString.call(1));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]

js 驗證數據類型的4中方法