簡體   English   中英

JavaScript 中的三元運算符條件為真時才賦值

[英]Assign only if condition is true in ternary operator in JavaScript

是否可以在 JavaScript 中做這樣的事情?

max = (max < b) ? b;

換句話說,只有在條件為真時才賦值。 如果條件為假,則什么都不做(不賦值)。 這可能嗎?

然后不要使用三元運算符,它需要第三個參數。 如果您不想更改max = (max < b) ? b : max則需要將max重新分配給max

if 語句要清楚得多:

if (max < b) max = b;

如果你需要它是一個表達式,你可以(ab)使用AND的短路評估:

(max < b) && (max = b)

順便說一句,如果你想避免重復變量名(或表達式?),你可以使用maximum 函數

max = Math.max(max, b);

帶有三元運算符的表達式必須具有兩個值,即對於 true 和 false 情況。

不過你可以

max = (max < b) ? b : max;

在這種情況下,如果條件為假, max值不會改變。

如果條件為假,您可以將max設置為自身。

max = (max < b) ? b : max;

或者您可以嘗試使用&&運算符:

(max < b) && (max = b);

或者為了保持代碼簡單,只需使用if

if(max < v) max = b;

我認為三元更合適試試這個

(max < b) ? max = b : '';

沒有不是三元運算符的特定運算符,但您可以像這樣使用它:

max = (max < b) ? b : max;

我認為更好的方法可能是

max = Math.max(max, b)

你可以這樣做:

(max < b) ? max = b : ''

你可以試試:

(max < b) && (max = b);

看看這個例子:

 let max = 10; let b = 15; (max < b) && (max = b)// this will be true console.log("max=", max); let maxx = 10 let bb = 5; (maxx < bb) && (maxx = bb)// this will be false console.log("maxx=", maxx);

三元運算符用於我們至少有兩個可能的結果。

let no = 10;
let max = 20;

max = no > max ? no : max

如果您只想使用 if 而不是 else,那么我建議您使用 if not 三元運算符。

let no = 10;
let max = 20;
    
if (no > max){
   max = no
}

如果你想使用三元運算符,但又不想使用 else 部分,那么你可以使用這個,但這並不是對每個問題都有用

let no = 10;
let max = 20;

no > max ? max = no : 0

在這里,我們僅在條件為真時才為 max 變量賦值,否則,我們什么也不做

績效結果

由於大多數答案幾乎告訴您幾乎所有可能的方法,這里是四種最常見方法的一些性能結果,超過 4000 萬次迭代,每種方法平均運行 10 次。

使用三元
對於a = b > a? b: a for iterations over 10 runs a = b > a? b: a 10 次運行中次迭代的平均時間為
for iterations over 10 runs 而對於(b > a) && (a = b) 10 次運行的次迭代,平均時間為

使用 Math.max
for iterations over 10 runs 對於a = Math.max(a, b)在 10 次運行中次迭代的平均時間為

使用 if 語句
for iterations over 10 runs 對於if (b > a) a = b 10 次運行中次迭代的平均時間為

看:

(max < b) ? max = b : null;

它會解決的,我想您想避免使用冒號,不幸的是,它不會發生

沒有ES6的例子,我們可以這樣使用:

let list = [{id: "abc", name: "test1"}, {id: "xyz", name: "test2"}]
let selectedData = {};
      list.some((exp) => {
        return (
          exp.id == "xyz" &&
          ((selectedData = exp), true)
        );
      })
console.log(selectedData);

投反對票后添加說明:只需添加說明來解釋我的解決方案。 如果您有一組對象,並且希望只有一個條件滿足,那么我們可以使用some id == "xyz"時,它將設置selectedData 正如問題中所問,僅當條件為真時才會賦值,否則selectedData將為空。

您可以使用邏輯與賦值 (&&=)代替三元運算符

基本示例

 let output = false; output &&= true; console.log(output)

無法重新分配,因為output已定義為false

 const b = 10; const max = 1; let sum = max < b; sum &&= 'new value'; console.log(sum);

返回一個字符串,因為變量sum已定義為true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM