js--類型判斷比較2

typeof instanceof object.prototype.toStringhtml

typeof 只能判斷基本類型:number string object undefined boolean

==typeof==

prototype

console.log(typeof(2),'test')  //number
console.log(typeof(true),'test') //boolean
console.log(typeof('2'),'test') //string
console.log(typeof([]),'test') //object
console.log(typeof({}),'test') //object
console.log(typeof(null),'test') //object
console.log(typeof(undefined),'test')
//undefined
function f() {}
console.log(typeof(f),'test') //function

==instanceof==(覺得很簡單,卻最複雜)設計

判斷變量是否爲某個對象的實例,返回值爲true或者false
<html>
<!--在這裏插入內容-->
    
    let o = {}
    console.log(a2 instanceof Object)  //true
    let a = []
    console.log(a3 instanceof Array) //true
    function f() {}
    console.log(f instanceof Function) //true
    console.log(true instanceof Boolean) //false
    console.log(1 instanceof Number) //false
    console.log('1' instanceof String) //false

</html>

你們能夠看到當涉及到值類型時,就會顯示"不太正常"code

var str = new String('000') var str2 = '000' console.log(str1 instanceof String) //true console.log(str2 instanceof String) //false console.log(str) //String{"000"} console.log(str2) //000

你們會發現不一樣方式的建立字符串,instanceof 卻不同?htm

因此instanceof 的工做原理到底是什麼呢?對象

規範定義的該運算符
<html>
<!--在這裏插入內容-->

     function instance_of(L, R) {//L 表示左表達式,R 表示右表達式
     var O = R.prototype;// 取 R 的顯示原型
     L = L.__proto__;// 取 L 的隱式原型
     while (true) { 
     if (L === null) 
     return false; 
     if (O === L)// 這裏重點:當 O 嚴格等於 L 時,返回 true 
     return true; 
     L = L.__proto__; 
     } 
    }

</html>
只有數據類型的隱式類型和顯式類型絕對相等時,纔會返回true

==這就設計到了原型鏈==了內存

這兩種方式均可以建立字符串,可是str是在堆內存中開闢一片新空間存放新對象,是有原型鏈的,str2是放在常量池中(沒有原型鏈的).原型鏈

1.若是常量池中已經有字符串常量」aaa」

經過方式二建立對象,程序運行時會在常量池中查找」aaa」字符串,將找到的「aaa」字符串的地址賦給a。

經過方式一建立對象,不管常量池中有沒有」aaa」字符串,程序都會在堆內存中開闢一片新空間存放新對象。

2.若是常量池中沒有字符串常量」aaa」

經過方式二建立對象,程序運行時會將」aaa」字符串放進常量池,再將其地址賦給a。

經過方式一建立對象,程序會在堆內存中開闢一片新空間存放新對象,同時會將」aaa」字符串放入常量池,至關於建立了兩個對象。

因此 new出來的會有原型屬性.而直接賦值的則沒有.字符串

==Object.prototype.toString.call()==原型

<html>
<!--在這裏插入內容-->
    
    console.log(Object.prototype.toString.call('1')) 
    console.log(Object.prototype.toString.call(1)) 
    console.log(Object.prototype.toString.call(true))
    console.log(Object.prototype.toString.call(null)) 
    console.log(Object.prototype.toString.call(undefined))
    console.log(Object.prototype.toString.call([]))
    var set = new Set();
    console.log(Object.prototype.toString.call(set))
    var map = new Map();
    console.log(Object.prototype.toString.call(map))
    console.log(Object.prototype.toString.call({}))
    function f2(){}
    console.log(Object.prototype.toString.call(f2))
    
    
    //output
    [object String]
    [object Number]
    [object Boolean]
    [object Null]
    [object Undefined]
    [object Array]
    [object Set] 
    [object Map]
    [object Object]
    [object Function]

</html>
因此用 Object.protoType.toString.call() 更準確

==記住Object.protoType.toString() 去查看類型都是Object,因此要用Object.protoType.toString.call()==

相關文章
相關標籤/搜索