数据类型(一)typeof、undefined、null

js的数据类型一共分七种,包括六种简单数据类型:Undefined、Null、Boolean、Number、String和Symbol(ES6新增),和一个复杂数据类型Object(对象)。

要判断这些数据类型,就需要用到typeof操作符。

typeof操作符

使用typeof操作符时会返回下面几个字符串之一:

  • undefined 表示未定义
  • boolean 表示布尔值
  • string 表示字符串
  • number 表示数字
  • object 表示对象或null
  • function 表示函数
  • symbol 表示值为符号

使用方法:

let message = 'some string'
console.log(typeof message); //string
console.log(typeof(message)); //string
console.log(typeof 96); //number
复制代码

输出为

image.png

注意:当typeof判断的值是null时,返回的是object

undefined类型

undefined类型只有一个值,就是特殊值undefined。
当使用var或let声明变量却没有将其赋值时,这些变量默认值就是undefined。

let message;
var age;
console.log(message); 
console.log(age); 
console.log(typeof message); 
console.log(typeof age); 
复制代码

输出

image.png
等同于直接赋值undefined,但是没有必要。

let message = undefined;
var age = undefined;
console.log(message);
console.log(age);
复制代码

image.png
但是值为undefined和没有声明是两回事。比如

let message;
console.log(message); 
复制代码

就会输出undefined。

image.png
未定义就输出age

console.log(age); 
复制代码

image.png
就会报错,变量未定义。

let message;

if(message){
    //这个块不会执行
}

if(!message){
    //这个块会执行
}

if(age){
    //这里会报错
}
复制代码

null类型

null类型同样也只有一个值,就是特殊值null。逻辑上讲,null是一个空对象指针,这也是给typeof传一个null会返回”object”的原因:

let car = null;
console.log(typeof car);
复制代码

输出

image.png

在定义将来要保存对象的变量时,建议用null来初始化

所以以后只需要判断变量是否为null,就可以知道该变量是否被重新赋予对象

if(car !== null){}
复制代码

undefined是由null派生来的,所以它们表面相等

console.log(undefined == null); //tree
复制代码

null是一个假值,如果需要,可以用更简洁的方式区分。不过,有很多其他的假值,一定要确认自己检测的就是null,而不仅仅是假值。

let message = null;
let age;

if(message){
    //这个块不执行
}

if(!message){
    //这个块执行
}

if(age){
    //这个块不执行
}

if(!age){
    //这个块执行
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享