簡體   English   中英

條件三元運算符 React.js,Javascript(數據結構)

[英]Conditional Ternary Operator React.js, Javascript (Data Structures)

我正在處理這個React.js 文檔,並在這里對這段代碼有疑問: Codepen。

我一直對使用的條件三元運算符感到困惑。 下面是:

const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;

據我了解,這行代碼的工作方式如下:

if (scale === "f") {
  const celsius = tryConvert(temperature, toCelsius);
} else 
  return temperature;
}

if (scale === "c") {
  const fahrenheit = tryConvert(temperature, toFahrenheit);
} else 
  return temperature;
}

正如您會在 Codepen 網站上注意到的那樣,一旦更改了攝氏度,那一刻華氏度也會更改。 我對代碼的理解表明,如果正在更改的刻度等於“c”,則將溫度轉換為華氏溫度,否則不要修改溫度值。

我試圖刪除原始的 const fahrenheit 並將其寫成一個簡單的 if else 語句,就像我上面所說的那樣,但它不起作用。

有人可以幫我確定我寫的 if else 語句中的錯誤在哪里嗎? 我想將條件三元運算符理解為 if else 語句。

對於您的if / else塊到 function 類似於上面示例中所示的三元組,您必須這樣做。

render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    
    // This assignment effectively covers the else part in the ternary.
    let celsius = temperature;
    let fahrenheit = temperature;
    
    if(scale === 'f') {
        celcius = tryConvert(temperature, toCelsius);
    }
    if(scale === 'c') {
        fahrenheit = tryConvert(temperature, toFahrenheit);
    }
    
    return (
    // do stuff

您在此處使用的“簡單” if else 語句的問題在於,變量是用“const”聲明的,這使得它們在塊的 scope 中是本地的(由大括號分隔)。 如果 function 中的 function 位於 function 中, return語句也將停止執行,在 function 之外return是沒有意義的。

您可以做的是在條件之前將聲明帶到外面:

let celsius, fahrenheit;
if (scale === "f") {
  celsius = tryConvert(temperature, toCelsius);
} else 
  celsius = temperature;
}

if (scale === "c") {
  fahrenheit = tryConvert(temperature, toFahrenheit);
} else 
  fahrenheit = temperature;
}

現在這就是三元形式可以翻譯的內容。

暫無
暫無

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

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