美文网首页javascript要点须知
JS中null 与 undefined异同及使用情况

JS中null 与 undefined异同及使用情况

作者: 西游复西行 | 来源:发表于2018-03-15 18:05 被阅读0次
相同
 
二者几乎是等价的

undefined、null在 if语句中都可以当成false使用

if (!undefined) {
  console.log('undefined is false');
}
// undefined is false

if (!null) {
  console.log('null is false');
}
// null is false
不同

不过还是有小小的不同

1、数据类型 
     typeof null //返回“object”
     typeof undefined //返回"undefined"

2、进行数值运算时
     5+"null" //返回5,null转换为0
     5+"undefined" //返回NaN,undefined转换为NaN

3、用法及含义(null表示“空值”,undefined表示“未定义”)

      #null
      调用函数时,某个参数未设置任何值,这时就可以传入null
      function f1(x,y){return x}
      f1(4,null); //5
      f1(4); //5

      #undefined
      #以下情况会返回undefined

      --- 声明变量,但没有赋值,会返回undefined
            var x;
            x; // undefined

      ---  对象没有赋值的属性
            var x ={};
            x.p; // undefined

      ---  函数无返回值
            function f(){};
            f()// 默认返回undefined

      ---  调用函数时,应该提供的参数没有提供,该参数等于 undefined
            function f(x){return x};
            f()// undefined

      ---  typeof 未声明、未赋值的变量(可以使用这个方法判断某个变量是否存在)
            typeof v // undefined
            if(typeof v === "undefined"){
                // ...正确写法
            }
            if(v){
                // ...错误写法,ReferenceError: v is not defined
            }

本文为阅读阮一峰大神《JavaScript标准参考教程》之后写的总结,如果大家觉得有不清楚的,可以去看大神写的教程😀

相关文章

网友评论

    本文标题:JS中null 与 undefined异同及使用情况

    本文链接:https://www.haomeiwen.com/subject/ejghqftx.html