使用多個 or 運算子時如何簡化代碼。我有一個從 0 到 6 的數字串列,用邏輯或分隔。有沒有辦法簡化它?
if (filteredMnth === 'mnth') {
return (new Date(exp?.date).getMonth().toString() === "0" || "1" || "2" || "3" || "4" || "5" || "6" )
}
uj5u.com熱心網友回復:
一個很好的模式是創建一個validoraccepted值的陣列,并使用Array.prototype.includes來檢查用戶輸入中的一個:
const validValues = [ 0, 1, 2 ];
const input = 2;
validValues.includes(input);
// => true
const input2 = 3;
validValues.includes(input2);
//=> false
正如@Robby Cornelissen 在評論中已經提到的那樣,在您的情況下,它確實沒有任何意義,但我在此處包含此模式以回答您問題的更通用版本。
uj5u.com熱心網友回復:
首先要小心
(month === "0" || "1" || "2" || "3" || "4" || "5" || "6" || "7" || "8" || "9" || "10" || "11")
不會回傳布林值,但如果月份不等于 0,它將回傳“1”
function wrongValidateMonth(month) {
return (month === "0" || "1" || "2" || "3" || "4" || "5" || "6" || "7" || "8" || "9" || "10" || "11")
}
console.log(wrongValidateMonth("0"));
console.log(wrongValidateMonth("1"));
一個想法可以是構造一個包含所有有效月份數的陣列,并查看月份是否包含在該陣列中
function runningValidateMonth(month) {
let monthList = Array.from(Array(12).keys());
return (monthList.some(oneMonth => oneMonth.toString() === month));
}
console.log(runningValidateMonth("0"));
console.log(runningValidateMonth("1"));
console.log(runningValidateMonth("25"));
uj5u.com熱心網友回復:
由于您有多個值,您可以使用 List 并包含如下方法
const validMonths = ["1", "2", ...]
const monthToCheck = new Date(exp?.date).getMonth().toString()
if(validMonths.includes(monthToCheck)){
//Evaluates true if value exist
}
uj5u.com熱心網友回復:
對于這種特定情況,您可以執行 ->
if (filteredMnth === 'mnth') {
return new Date(exp?.date).getMonth() <= 6;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/456311.html
標籤:javascript 反应 jsx 逻辑运算符
