[英]Alternative way to write if statement in javascript
我正在縮小我的javascript代碼,我想知道是否有更多的方式來編寫這個巨大的if語句:
if (operator_list == "=" || operator_list == "<>" || operator_list == ">" || operator_list == "<" || operator_list == ">=" || operator_list == "<=" )
有任何想法嗎?
使用數組並檢查它是否包含operator_list
let checkArr = ["=", "<>", ">", "<", ">=", "<="];
if (checkArr.includes(operator_list)) {}
你可以為它采取正則表達式。
function test(s) { return /^(=|<>|>|<|>=|<=)$/.test(s); } console.log(["=", "<>", ">", "<", ">=", "<=", 'foo', '<a='].map(test));
我認為將表達式重構為函數並賦予它一個好名稱會使它更優雅:
if (isValidOperator(operator_list) ) {
// Do something
}
function isValidOperator(operator) {
return operator == "=" || operator == "<>" || operator == ">" || operator == "<" || operator == ">=" || operator == "<=";
}
通過這種方式,您可以向讀者解釋您的代碼的用途。 在稍后階段,有人可以重構函數以使其更容易理解。
其他讀物:
您可以創建可接受的運算符數組
var arr = [ "=", "<=" ];
然后檢查operator
是否是數組的元素之一
arr.indexOf( operator_list ) != -1 //will return true if operator_list is in arr
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.