JavaScript 五种基本数据类型(上)

如未作出特殊说明,本文例子均在Chrome控制台进行测试。本系列文章只探讨es6之前的基本数据类型,es6新增数据类型Symbol放在文章ES6必知必会中。
###一、哪五种基本数据类型?
null、undefined、number、boolean、string。undefined是null的子集。
###二、如何判断变量的数据类型?

  • 使用 typeof 运算符,Chrome控制台结果:
typeof "1";
"string"

typeof 1;
"number"

typeof 1.1  //浮点数类型也为number
"number"

注意事项:Math.round(-1.5);//-1 ,数值+0.5后,向下取整。

typeof true;
"boolean"

typeof null; //表示空对象指针
"object"

typeof undefined
"undefined"

typeof a
"undefined"
  • 如何判断变量的数据类型是否为 null?
    使用严格等于“===”,比如 :
a === null
true

###三、类型转换

隐式(自动)类型转换
  • 举例:
"a" + 1
"a1"

1+1.1
2.1

0 && true
0

null +0.1
0.1

null && true
null

null && undefined
null

1 + undefined
NaN

null + undefined
NaN
  • 转换场景:
    (1)if 语句
var a1 = ' ';
if(a1){//a1被转换成false
//此处代码不会执行
}
--------------------------
var a2 =2;
if(a2){//a1被转换成true
//此处代码会执行
}

(2)字符串拼接

所有操作数类型都会被转换成字符串类型,结果也都是字符串类型。

(3)逻辑运算

2&&0
0

'' || 'a'
"a"

!document.a //document.a为undefined,取反操作将undefined转换为false,因此结果为true
true

“奇技淫巧” :判断一个变量会被当做作false或者true
例如:var b = 1024
     !!b
     true

(4)“==” 运算符

   1=='1'
   true

   "1"==true// string和boolean类型都转换成number类型,此处均转换成1
   true

   0==false
   true

   0==' ' //0和空字符串都被转换为false
   true

   null==undefined  //undefined派生于null,关键是两者都被转换成了false
   true

(5)“=” 运算符与“” 运算符
使用条件语句时除了判断变量是否为null之外,其余数据类型判断都用“===”。
例如:

var a;
if(a==null){

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值