数据类型的判断
typeof
typeof是经常使用的一种数据判断方式,可以准确判断基本数据类型(除了null,会被判断为Object),因为在早期的js中,数据类型是根据机器码的前三位来判断的,前三位为0的就是Object,而null正好全部位数都为0. typeof除了判断函数正确,其余都会被判断为Objcet.所以一般用来判断基本数据类型.
instanceof
instanceof用来判断引用类型,因为他的原理是根据原型链来查找左侧实例的(
__proto__)与右侧的(prototype)是否是相等的,直到查找到相等的或者原型为null,所以并不能用来判断基本类型.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18function myInstanceof(left,right){
// if(!left) return false
// if(left.__proto__==right.prototype) return true
// else{
// return myInstanceof(left.__proto__,right)
// }
let leftValue = left.__proto__
let rightValue = right.prototype
while(1){
if(leftValue===null) return false
if(leftValue==rightValue) return true
leftValue=leftValue.__proto__
}
}
let obj = []
console.log(myInstanceof(obj,Object));constructor
constructor可以获取变量的构造函数,能判断绝大多数的类型,没有构造函数的就判断不了(null,undefined,Object.create(null)…)
1
2"1".constructor===String
"1".constructor.name//"String"Object.prototype.toString.call()
利用call方法改变this指向,借用对象原型上的toString(),可以判断所有类型

ps:顺便记录下所有类型原型上的toString()
Number.prototype.toString(radix)
radix(2~36),代表这个数字的进制,超出会报RangeError
1
2
3let count = 10
count.toString()//'10'
count.toString(2)//'1010'String.prototype.toString()
1
2
3var x = new String("Hello world");
alert(x.toString()) // 输出 "Hello world"Array.prototype.toString()
1
2
3
4const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// expected output: "1,2,a,1a"Function.prototype.toString()
返回表示函数源代码的字符串
1
2
3
4
5
6
7
8function sum(a, b) {
return a + b;
}
console.log(sum.toString());
// expected output: "function sum(a, b) {
// return a + b;
// }"
为什么0.1+0.2!==0.3
在js中没有整数的概念,都是浮点数.而计算机运算时,会把数字转换为二进制.浮点数转为二进制可能会产生无限循环小数(乘以2,取整数位),Number类型遵守IEEE754标准,总共64位,1位符号位(0表正,1表负),11位指数位,52位尾数位,超出的会被截断,进1舍0。
解决办法:
- toFixed()
- 自定义函数(把小数放大为整数再进行计算)
- 自定义函数(设置误差,相减的绝对值没超过2的负52次方)
isNaN()和Number.isNaN()的区别
- isNaN()会进行类型转换,如果能转换为数字,就返回true,判断不准确
- Number.isNaN()先判断是否为number类型(NaN也是number类型),不是就返回false,是的话就在判断是否为NaN,不会进行数据类型转换
1 | console.log(isNaN(NaN)) //true |
==类型转换的规则
- 如果数据类型相同,返回true
- 如果是null和undef,返回true
- 如果是number和string,把string转为number
- 如果是number和boolean,把boolean转为number
- 如果一方是object,另一方是string number symbol,把object–> 原始类型。
强制类型转换的规则
(1)其他值–>字符串:Null、Undefined、Boolean、Number、Symbol都是直接转换为字符串,加上双引号,对于普通对象来说,一般会用toString()转换为内部属性[[Class]]的值;
(2)其他值–>数字值:①Undefined类型的值转换为NaN,Null类型转换为0,true为1,false为0,String如果包含非数字就为NaN,否则为数字,空字符串为0,Symbol会报错;
(3)其他值–>布尔值:false值包括(undefined,null,false,+0,-0,NaN,“”),其他值都是真值。