[英]set multiple conditions in ternary operator
我想設置一個條件,它不應該大於 10 或小於 0,但我不明白如何在三元運算符中設置
var count = 0;
var res = flag == "1" ? ++count : flag == "0" ? --count;
每個條件都返回一個結果。 讓我們嘗試添加一些格式。 您缺少最后一個條件的最終 else 語句。
var count = 0;
var res =
flag == "1"
? ++count
: flag == "0"
? --count
: doSomethingElse
不管怎樣,根據你寫的,你希望你的數字是 0-10。 我們不使用++
和--
直到我們確定要寫入值。 如果超出范圍,我們只需返回原始count
數值。
var res =
(count + 1) < 10
? count++
: (count - 1 < 0)
? count--
count
或者,在單行形式中,您可以這樣寫:
for (let flag=1,count=-4, i=-3; i<15; i++) console.log(i, i>=0? i<=10? true: false: false, // using ternary operators i>=0 &&i<=10, // a better way of achieving the same result Math.min(Math.max(i,0),10), // maybe this is what you want? Math.min(Math.max(flag?++count:--count,0),10) // or this? )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.