JS中的数据类型及检测

基本数据类型(值类型)
number:数字
string:字符串
boolean:布尔
null:空对象指针
undefined:未定义
引用数据类型
1、 object对象数据类型
{}普通对象
[]数组
/^KaTeX parse error: Expected 'EOF', got '\d' at position 179: …12,23,34] /^-?(\̲d̲([1-9\d+))(\.\d…/
function fn(){}
这么多数据类型JS如何去检测呢?
-typeof:检测数据类型的运算符
-instanceof:检测某个实例是否属于这个类
-constructor:获取当前实例的构造器
-Object.prototype.toString.call:获取当前实例的所属类信息
typeof
使用typeof 检测,返回的结果是一个字符串,字符串中包含的内容证明了值是属于什么类型的;
【局限性】
1、 typeof null 的结果不是“null" 而是”object“ : 因为null虽然是单独的一个数据类型,但是它原本意思是空对象指针,浏览器使用typeof检测的时候会把它按照对象来检测
2、 无法具体细分出到底是数组还是正则,因为返回的结果都是“object”
typeof 12 =>“number”
typeof “hehe” =>“string”
typeof true =>“boolean”
typeof null =>“object”
typeof undefined =>“undefined”
typeof {name:‘hehe’} =>“object”
typeof function(){} =>“function”
typeof [] =>“object”
typeof /^$/ =>“object”
console.log(typeof typeof []); => “string”
布尔类型详细解读
Boolean()
把其他数据类型的值转换为布尔类型
只有 ’ 0、NaN 、空字符串 、null 、undefined ‘ 这五个数据值转换为布尔类型的false,其余的都会变为true;


!=   不等于
叹号在JS中还有一个作用:取反,先把值转换为布尔类型,然后再去取反
!1 =>  false;
![] =>  false;
!0 =>  true;
!!
在一个叹号取反的基础上再去反,去两次反相当于没有做操作,但是却已经把其他类型值转换为布尔类型了,和Boolean是相同的效果。
!!1 => true;
!![]=> true;
!!0 => false;
字符串
在JS中 单引号 和 双引号 包起来的都是字符串
12 ->  number
‘12’ -> string
“[12,13]” -> string
常用方法:
charAt  charCodeAt
substr substring alice
toUpperCase toLowerCase
indexOf lastIndexOf
split
replace
match

number数字
0 , 12 , -12 , 12.5 ,    JS中多增加了一个number类型的数据:NaN
typeOf NaN ->  “number”
NaN
not a number :不是一个数,但是数据number类型
NaN == NaN  // false ,  NaN和任何其他值都不相等
isNaN()
用来检测当前这个值是否是非有效数字,如果不是有效数字检测的结果是true,反之是有效数字则为false;
isNaN(0)  =>  false
isNaN(NaN)  =>  true
isNaN(“12”)  =>  false  当我们使用isNaN检测值得时候,检测的值不是number类型的,浏览器会默认的把值先转换为number类型,人后再去检测
Number()
把其他数据类型值转换为number类型的值
Number(“12”) -> 12
Number(“12px”) -> NaN   // 在使用Number转换的时候只要字符串中出现任何一个非有效数字字符,最后的结果都是NaN
Number(true) -> 1
Number(false) -> 0
Number(null) -> 0
Number(undefined) -> NaN

Number([]) -> 0  ->  把引用数据类型转换为number,首先要把引用数据类型转换为字符串(toString),再把字符串

猜你喜欢

转载自blog.csdn.net/weixin_44462907/article/details/88642975