三元表达式当判断为真值不改变应该怎么写更合理

不会跳青蛙
  • 196

比如:

getCookie("home_voice") ? true : setCookie("home_voice",0);

给true感觉怪怪的,请问有更合适的吗?不知道给空字符串("")可行吗?

回复
阅读 618
5 个回答
✓ 已被采纳

getCookie("home_voice") || setCookie("home_voice",0)

空字符串不行,因为用 if 判断,空字符串会返回 false

用or就行了

getCookie("home_voice") || setCookie("home_voice",0);
getCookie("home_voice")?getCookie("home_voice"):setCookie("home_voice",0);

那你为什么还要用三元?楼上正解
若是真执行,则用getCookie("home_voice") && setCookie("home_voice",0)
若非真执行,则用getCookie("home_voice") || setCookie("home_voice",0)
仍要用则
getCookie("home_voice") ? console.log(“getCookie("home_voice")=true”) : setCookie("home_voice",0);
便于调试

你知道吗?

宣传栏