【轉】ES6對象類型判斷


數組對象

var arr=[{"name":"ls","age":12},{"name":"jason","age":22},12];

1、 typeof 判斷

console.log( typeof arr)
console.log( typeof arr=='object')
//typeof的一個不好的地方就是它會把Array還有用戶自定義函數都返回為object

 

typeof方法只能判斷基本類型類型(number, string, undefined,boolean),除此之外(包括Date, RegExp,null等都只是object的擴展!)都不靠譜

數組一般情況下可以用instanceof來判斷。

2、構造函數指針 判斷

console.log(arr.constructor.name) console.log(arr.constructor.name==Array) console.log(arr.constructor.name=='Array') //打印構造函數指針 console.log(a.constructor) function Array() { [native code] } //打印Array函數 console.log(Array) function Array() { [native code] } //兩個完全一致的函數作比較 console.log(a.constructor==Array) true 

3、instranceof 判斷

console.log( arr instanceof Array) //利用typeof和constructor進行嚴格判斷  console.log((typeof arr=="object") && (arr.constructor==Array))  console.log((typeof arr=="object") && (arr.constructor.name=='Array')) 

4、原型函數 判斷

console.log(Object.prototype.toString.call(arr)); //封裝改進后的函數 console.log(type(arr)); var class2type = {},     //用於記錄[object class]樣式   objs = "Boolean Number String Function Array Date RegExp Null Undefined".split(" ");   for (var i = 0, l = objs.length; i < l; i++) {        class2type[ "[object " + objs[i] + "]" ] = objs[i].toLowerCase();   }   function type(obj) {        return class2type[ Object.prototype.toString.call(obj) ] || "object";   }


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM