最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to declare a variable in a ternary expression? - Stack Overflow

programmeradmin1浏览0评论

I need to set i depending on a condition:

let i = null
nightmode === true ? i = 1 : i = 0

Is it possible to declare i within the ternary expression, or does it have to be in outside of it (to handle scoping)?

I need to set i depending on a condition:

let i = null
nightmode === true ? i = 1 : i = 0

Is it possible to declare i within the ternary expression, or does it have to be in outside of it (to handle scoping)?

Share Improve this question asked Dec 16, 2018 at 14:58 WoJWoJ 30.1k58 gold badges214 silver badges405 bronze badges 1
  • 2 Your ternary is using a side effect instead of how it was designed to be used. let i = nightmode === true ? 1 : 0 – mplungjan Commented Dec 16, 2018 at 14:59
Add a ment  | 

2 Answers 2

Reset to default 5

You could use the ternary directly as assignment for the value.

let i = nightmode === true ? 1 : 0;

I think your variable i needs to be outside of it, although it is possible to set i in the following manner:

let nightmode = true;
let i = (nightmode === true) ? 1 : 0
console.log(i);

发布评论

评论列表(0)

  1. 暂无评论