我想知道JavaScript中null和undefined之间的区别。


当前回答

由于typeof返回undefined,undefineed是一种类型,其中null是一个初始值设定项,表示变量指向任何对象(实际上Javascript中的所有内容都是一个对象)。

其他回答

null是一个特殊的关键字,表示缺少值。

将其视为一种价值,例如:

“foo”是字符串,true为布尔值,1234是数字,null未定义。


undefined属性表示尚未为变量分配包含null的值。喜欢

var foo;

定义的空变量为null,数据类型为undefined


它们都表示一个没有值的变量的值

以及null不表示没有值的字符串-空字符串-


Like

var a = ''; 
console.log(typeof a); // string 
console.log(a == null); //false 
console.log(a == undefined); // false 

现在如果

var a;
console.log(a == null); //true
console.log(a == undefined); //true 

BUT

var a; 
console.log(a === null); //false 
console.log(a === undefined); // true

所以每个人都有自己的使用方法

undefined使用它来比较变量数据类型

null使用它来清空变量的值

var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object 

看看这个。输出值一千字。

var b1=文档.getElementById(“b1”);checkif(“1,无参数”);checkif(“2,显式未定义”,未定义);checkif(“3,显式空”,空);checkif(“4,the 0”,0);checkif(“5,空字符串”,“”);checkif(“6,string”,“string”);checkif(“7,number”,123456);函数checkif(a1,a2){print(“\ncheckif(),”+a1+“:”);如果(a2==未定义){打印(“==未定义:是”);}其他{打印(“==未定义:否”);}如果(a2==未定义){打印(“==未定义:是”);}其他{打印(“==未定义:否”);}如果(a2==空){打印(“==null:YES”);}其他{打印(“==null:NO”);}如果(a2==空){打印(“==空:是”);}其他{打印(“==null:NO”);}如果(a2==“”){打印(“=='':是”);}其他{打印(“=='':否”);}如果(a2==“”){打印(“=='':是”);}其他{打印(“=='':否”);}如果(isNaN(a2)){打印(“isNaN():是”);}其他{打印(“isNaN():否”);}如果(a2){打印(“如果-?:是”);}其他{打印(“如果-?:否”);}打印(“typeof():”+typeof(a2));}函数打印(v){b1.innerHTML+=v+“\n”;}<!DOCTYPE html><html><body><pre id=“b1”></pre></body></html>

另请参见:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefinedhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaNhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/nullhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

干杯

基本上,Undefined是javascript在运行时创建的一个全局变量,无论null是否意味着没有给变量赋值(实际上null本身就是一个对象)。

让我们举个例子:

        var x;  //we declared a variable x, but no value has been assigned to it.
        document.write(x) //let's print the variable x

未定义,这是您将获得的输出。

现在

        x=5;
        y=null;
        z=x+y;

你将得到5作为输出。这是Undefined和null之间的主要区别

const data  = { banners: null }
const { banners = [] } = data;
console.log(data)      // null


const data  = { banners: undefined }
const { banners = [] } = data;
console.log(data)      // []

由于typeof返回undefined,undefineed是一种类型,其中null是一个初始值设定项,表示变量指向任何对象(实际上Javascript中的所有内容都是一个对象)。