在javascript中判断一个对象下的数组属性时,时常会出现这样的误写,请仔细想一下这两种写法的异同:
if (t.ccc && t.ccc.length === 0)
if (!t.ccc || t.ccc.length === 0)
通常我们是想判断当这个数组里有没有东西,如果有则做什么,但第一种写法实际隐含着问题,不注意时经常会想错。
测试如下:
var t = {};
console.debug(t.ccc == undefined);
// true
if (t.ccc && t.ccc.length === 0){console.debug("ok")} else {console.debug("error")}
// error
if (!t.ccc || t.ccc.length === 0){console.debug("ok")} else {console.debug("error")}
// ok