[英]Convert if statement to ternary operator
我試圖將這些if語句轉換為三元:
var eatsPlants = false;
var eatsAnimals = true;
if(eatsPlants){
return 'herbivore';
}else if(eatsAnimals){
return 'carnivore';
}else if(eatsPlants && eatsAnimals){
return 'omnivore';
}else{
return undefined;
}
這是我的解決方案:
var category = eatsPlants && eatsAnimals ? "omnivore" : "herbivore" : "carnivore" : undefined;
console.log(category);
但這不起作用,它返回錯誤的分號。
知道如何解決嗎?
您忘記了其他兩個條件,並更改了檢查順序(盡管這實際上是使其工作所必需的)。 你要么做
return (eatsPlants && eatsAnimals
? 'omnivore'
: (eatsPlants
? 'herbivore'
: (eatsAnimals
? 'carnivore'
: undefined)));
或者,通過嵌套避免AND操作,
return (eatsPlants
? (eatsAnimals
? 'omnivore'
: 'herbivore')
: (eatsAnimals
? 'carnivore'
: undefined));
(括號和縮進是可選的,但出於可讀性考慮,強烈建議至少使用其中之一)。
if
條件也應該添加其余的
var category = eatsPlants && eatsAnimals ? "omnivore" : eatsPlants? "herbivore" : eatsAnimals? "carnivore" : undefined;
console.log(category);
您共享的js代碼段可能會引發錯誤,因為return語句不在函數內部。
已經創建了另一個變量returnResult
,該變量將根據條件使用新值進行賦值。
!1為假&!0為真,void 0未定義
var eatsPlants = !1, eatsAnimals = !0, returnResult = "";
returnResult = eatsPlants ? "herbivore" : eatsAnimals ? "carnivore" : eatsPlants && eatsAnimals ? "omnivore" : void 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.