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

如未作出特殊说明,本文例子均在Chrome控制台进行测试。

一、哪五种基本数据类型?

null、undefined、number、boolean、string。

二、如何判断变量的数据类型?

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

typeof 1;
"number"

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

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)字符串拼接
“`js
所有操作数类型都会被转换成字符串类型,结果也都是字符串类型。

3)逻辑运算
```js
2&&0
0

'' || 'a'
"a"

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

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




<div class="se-preview-section-delimiter"></div>

(4)“==” 运算符

   1=='1'
   true

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

   0==false
   true

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

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

猜你喜欢

转载自blog.csdn.net/bengxu/article/details/80222424