JavaScript

JavaScript中的undefined和NULL以及空字符串3者的异同

一undefined

1 定义

从字面意思理解,这是一个未定义的东西。需要注意的是,它既可以用来表示变量的值是undefined,也可以用来表示变量本身的数据类型是undefined。

如:

//注意,此时只是声明了一个变量car,那么没给它赋值之前,它的value和data type都将是undefined
let car;
console.log("value of car:"+car+" data type of car: "+typeof car);
//value of car:undefined data type of car: undefined
2 赋值之后,其value和data type不再是undefined
//注意,此时只是声明了一个变量car,那么没给它赋值之前,它的value和data type都将是undefined
let car;
console.log("value of car:"+car+" data type of car: "+typeof car);
car = 1001;
console.log("value of car:"+car+" data type of car: "+typeof car);
//value of car:1001 data type of car: number
car = 'Volvo';
console.log("value of car:"+car+" data type of car: "+typeof car);
//value of car:Volvo data type of car: string
3 任意变量被赋值undefined,其value和data type都是undefined
car=undefined
console.log("value of car:"+car+" data type of car: "+typeof car);
//value of car:undefined data type of car: undefined

二空字符串

空字符串就是空字符串,它跟undefined没有任何关系。

空字符是有值的,只是它的值本身就是空字符串。并且它也有数据类型,是string。

An empty value has nothing to do with undefined.

An empty string has both a legal value and a type.

let car="";
console.log("value of car : "+car+"The data type of car is: "+type of car)
//value of car: data type of car:string

三NULL

In JavaScript null is “nothing”. It is supposed to be something that doesn’t exist.

Unfortunately, in JavaScript, the data type of null is an object.

在JavaScript中,NULL被认为是不存在的。

需要注意的是,==某个变量一旦被赋值为null,那么该变量的值本身是null,变量的数据类型却是object。==

You can consider it a bug in JavaScript that typeof null is an object. It should be null.

You can empty an object by setting it to null.

let car = {type:'Volvo',length:4.6};
console.log("value of car:"+car+" data type of car:"+typeof car);
//value of car:[object Object] data type of car:object
car=null
console.log("value of car:"+car+" data type of car:"+typeof car);
//value of car:null data type of car:object

You can also empty an object by setting it to undefined.Now both the value and data type are undefined.

四 undefined和NULL的区别

undefined和null的值是相等的,但是类型绝对不同。

let car;    //此时变量car的值和数据类型都是undefined;
let rocket = null;     //此时rocket的值是null,但是它的数据类型typeof 是object。
car == rocket;   //结果是true
car === rocket;  //结果是false

五参考链接

https://www.w3schools.com/js/js_typeof.asp

留言