首页 > undefined 与 null

undefined 与 null

图片描述`
//这是zepto源码中的一个函数
function compact(array) {

    return array.filter(function(item) {
        //下面这句话我觉得是否有些冗余??
        //undefined==null
        //所以是不是可以直接 return item !=null??
        return item !== undefined && item !== null
    })
}

function compact(array) {

    return array.filter(function(item) {
        return item != null
    })
}
还有,想告诉我 `0==null` 或者 `false==null`的同学,请把你的测试截图发上来。 ![图片描述][1]


undefined !== null // true !!!

undefined==null;//true
0==null;//false
0==undefined;//false

null和undefined在执行比较的时候不会做类型转换,也就其不会转成数学或字符串或boolean

!=是==的求反值
element!=null;在element在null/undefined的情况下返回false,其它情况下返回true

所以以上替换是可以的


按你第二种写法是可以,但是第一种更易读。


在n===undefined的时候,n===null也是成立的,所以按理说直接写item!=null也是可以的。但是由于0==null,所以看来这样写还是有缺陷的,也就是说他那样是有道理的。


变量的值undefined有两种情况:

  1. 当访问未定义的变量时: 表示该变量不存在,如果在C语言中访问一个不存在的变量, 会报错, javascript 对待一个不存在的变量为 undefined.

  2. 当定义了变量但未给其赋值时, 例如在Chrome中的测试:

var test2;
console.log(test1); // 变量`test1` 未定义
// 输出为 `undefined`
console.log(test2);
// 输出为`undefined`

// 变量 test1 未定义, 值为 undefined, test2 变量已定义但未赋值, 其值也为 undefined

null 表示一个变量的值为null

var test3 = null;
console.log(test3);
// 输出为`null`

如果你把test1, test2, test3 作为变量放入数组中, 其值是有可能为 undefinednull 的, 因此上面的判断并非是冗余的.


可以直接 item != null, 不是 !==

他这样写方便阅读啊。


我认为第一段代码的真正意图是为了防止过滤掉值为false或0等与undefined或null等价的值


并不等价,取 item = 0

0 == null

原答案有误,两者应该是等价的。

在使用==进行相等性判断时,与null相等的只有undefined和它自身,与undefined相等的只有null和它自身。

所以,如果item != null,那么说明item一定不是null且不是undefined

所以两者等价。

参考:11.9.3 The Abstract Equality Comparison Algorithm

原答案:
不可以。
两者并不等价。举个反例就清楚了:比如item0时,原表达式为true,而你给的表达式为false


我觉得可以这样写:!!item


这里不能用这种方法。。这种方法用来将一个值或对象转换为布尔值。

item !== undefined && item !== null这个语句返回一个布尔值,只有itemundefined或者null时,这个语句才会返回false。这样看来的话,这句话只能这么写。


undefined != undefined;    //false
undefined != null;    //false
undefined != 0;    //true
undefined != '';    //true
undefined != false;    //true
undefined != new Object();    //true
null != null;    //false
null != 0;    //true
null != '';    //true
null != false;    //true
null != new Object();    //true

实测得到的结果,题主的方法是可以的。

【热门文章】
【热门文章】