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()==

相关文章
相关标签/搜索