簡體   English   中英

在 Javascript if-else 語句中包含“或”的多個條件

[英]Multiple criteria with including 'or' in Javascript if-else statement

我是 Javascript 的新手。 嘗試編寫 function ,我將在其中輸入三個項目的值,它將返回總價。 如果我為任何參數輸入負值,它將給出錯誤消息而不是總價。

預期結果偽代碼:

如果 pen < 0 或 pencil < 0 或 sharpner < 0 那么 errorMessage 否則 totalPrice

我的代碼是:

function costCalc (pen, pencil, sharpner){

var penPrice = pen * 10;
var pencilPrice = pencil * 20;
var sharpnerPrice = sharpner * 5;

if (penPrice < 0 || pencilPrice < 0 || sharpnerPrice < 0 ){
    return "Something went wrong."
} else{
    var totalPrice = penPrice + pencilPrice + sharpnerPrice;
    return totalPrice
    }
}

我在這里“返回”了兩次。 這段代碼可以嗎? 或者,我必須改變一些東西?

提前感謝您的合作。

問候。

是的,你正在做的很好。 從 function 返回的那一刻,其余代碼未執行, function 已“完成”。 實際上,從 function 返回並故意跳過 return 語句后的代碼是很常見的。

您的代碼沒有任何問題,但有其他實現方式。 一些示例供您參考,可能是:

/* 
 * `[item]Price` can be < 0 only if `[item]` < 0 so you can anticipate the check
 * in order to avoid unnecessary calculations
 */

function costCalcB(pen, pencil, sharpner) {
  if (pen < 0 || pencil < 0 || sharpner < 0) {
    return "Something went wrong."
  } else {
    const penPrice = pen * 10;
    const pencilPrice = pencil * 20;
    const sharpnerPrice = sharpner * 5;
    const totalPrice = penPrice + pencilPrice + sharpnerPrice;
    return totalPrice;
  }
}

/*
 * You can also avoid the `else` block
 */
 
 function costCalcC(pen, pencil, sharpner) {
  if (pen < 0 || pencil < 0 || sharpner < 0) {
    return "Something went wrong."
  }
  
  const penPrice = pen * 10;
  const pencilPrice = pencil * 20;
  const sharpnerPrice = sharpner * 5;
  const totalPrice = penPrice + pencilPrice + sharpnerPrice;
  return totalPrice;
}

/*
 * In case of error, you can also throw an exception rather than return
 */
 
 function costCalcD(pen, pencil, sharpner) {
  if (pen < 0 || pencil < 0 || sharpner < 0) {
    throw "Something went wrong."
  }
  
  const penPrice = pen * 10;
  const pencilPrice = pencil * 20;
  const sharpnerPrice = sharpner * 5;
  const totalPrice = penPrice + pencilPrice + sharpnerPrice;
  return totalPrice;
}

try {
    costCalcD(10, 10, -1);
} catch(e) {
    console.log(e);
}

暫無
暫無

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

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