数据类型及类型转换
JS的六大数据类型
JS有六种数据类型
1.基本数据类型:
Number 123
String ‘abc’
Boolean true,false
Undefined undefined
Null 空
2.复杂数据类型
Object { }
三大引用类型
Object { }
Array [ " " ]
Function
1.Number类型
Number类型包含整数和浮点数(浮点数数值必须包含一个小数点,且小数点后面至少有一位数字)两种值。
NaN:非数字类型。特点:① 涉及到的任何关于NaN的操作,都会返回NaN ② NaN不等于自身。
isNaN() 函数用于检查其参数是否是非数字值。
isNaN(123) //false
isNaN("hello") //true
2.String类型
字符串有length属性。
字符串转换:转型函数String(),适用于任何数据类型(null,undefined 转换后为null和undefined;toString()法(null,defined没有toString()方法)。
3.Boolean类型
该类型只有两个值,true和false
4.Undefined类型
只有一个值,即undefined值。使用var声明了变量,但未给变量初始化值,那么这个变量的值就是undefined。
5.Null类型
null类型被看做空对象指针,前文说到null类型也是空的对象引用。
6.Object类型
js中对象是一组属性与方法的集合。这里就要说到引用类型了,引用类型是一种数据结构,用于将数据和功能组织在一起。引用类型有时候也被称为对象定义,因为它们描述的是一类对象所具有的属性和方法。
JS的类型转换,强制转换和隐式转换
1.强制转换
通过String(),Number(),Boolean()函数强制转换
1 var str=123;
2 var str1='123';
3 console.log(typeof str); //number
4 console.log(typeof str1); //string
5 console.log(typeof String(str)); //string
6 console.log(typeof Number(str1)); //number
2.隐式转换
JavaScript的数据类型分为六种,分别为null,undefined,boolean,string,number,object。object是引用类型,其它的五种是基本类型或者是原始类型。我们可以用typeof方法打印来某个是属于哪个类型的。不同类型的变量比较要先转类型,叫做类型转换,类型转换也叫隐式转换。隐式转换通常发生在运算符加减乘除,等于,还有小于,大于等。
1 console.log(typeof '10') //string
2 console.log(typeof 11) //number
3 console.log('11' < 4 ) //false
1.字符串加数字,数字就会转成字符串。
2.数字减字符串,字符串转成数字。如果字符串不是纯数字就会转成NaN。字符串减数字也一样。两个字符串相减也先转成数字。
3.乘,除,大于,小于跟减的转换也是一样。
1 console.log(10+'20') //2010
2
3 console.log(10-'20') //-10 number
4 console.log(10-'one') //NaN not a number
5 console.log(10-'101a') //NaN
6 console.log(10*'20') //200 number
7 console.log('10'*'20') //200 number
8 console.log(20/'10') //2 number
9 console.log('20'/'10') //2 number
10 console.log('20'/'one') //NaN
关于==
1.undefined等于null
2.字符串和数字比较时,字符串转数字
3.数字为布尔比较时,布尔转数字
4.字符串和布尔比较时,两者转数字
console.log(undefined==null) //true console.log('0'==0) //true 字符串转数字 console.log(0==false) //true 布尔转数字 console.log('0'==false) //2个都转成数字 console.log(null==false) //false console.log(undefined==false) //false