var o={};if(o.x) o.x+=1;看属性是否存在方法的时候,看到这么一句,不知道后 o.x+=1 是什么意思啊
1 回答

慕森王
TA贡献1777条经验 获得超3个赞
因为if语句进行判断后只有一个操作,所以编码者就省略花括号了,为了避免可能的错误,最好不要图省事这样省略。
if(o.x) o.x+=1;
相当于
if(Boolean(o.x)){ o.x = o.x + 1;}
如果这段代码是想判断对象 o 是否存在属性 x 的话,这样写是不太好的,例如下面这种情况,o存在未定义x属性,if视作不存在x:
var o={x:undefined};if(o.x) o.x=1; alert(o.x); //undefined
你何以在 if 中这样用'x' in o
;或者这样用o.hasOwnProperty('x')
如果你想对o.x的真值假值分别做点什么:
var o={x:false};if('x' in o){ if(o.x){ //真值 }else{ //假值,x可能为false,undefined,null,'',+0,-0,NaN } }
添加回答
举报
0/150
提交
取消