是否可以將所有條件簡化為一個條件?
長代碼例如:
let one = 'one'
let two = 'two'
let three = 'three'
let four = 'four'
if(one = 'one'){
if(two = 'two'){
if(three = 'three'){
if(four = 'four'){
}
}
}
}
可以只有一行嗎?
uj5u.com熱心網友回復:
必須進行兩項更改
let one = 'one'
let two = 'two'
let three = 'three'
let four = 'four'
if(one === 'one' && two === 'two' && three === 'three' && four === 'four'){
}
第一個變化是添加&&
第二個變化是=
替換===
uj5u.com熱心網友回復:
我會通過將檢查提取到一個函式中來保持它的可讀性來接近它:
function checkMyInput(one, two, three) {
if (one !== 'one') return false;
if (two !== 'two') return false;
if (three !== 'three') return false;
return true;
}
if (checkMyInput('one', 'two', 'three')) {
// the code you want to run
}
我不一定會嘗試將它們連接在一行中。在編程中,你不會因為簡潔而獲得加分,但你通常會因為使某些東西可讀而獲得加分。早點回傳是一種選擇,可以使關于為什么某事決議為真或假的推理更容易理解。
并且checkMyInput
函式可以在其他地方提取,因此您不必一直查看它。
uj5u.com熱心網友回復:
根據您為此執行的變數數量,使用物件來保存鍵/值對可能更容易,然后撰寫一個輔助函式來迭代Object.entries
usingevery
以檢查每個鍵和值是否相同。
const obj = {
one: 'one',
two: 'two',
three: 'three',
four: 'four'
};
function keyValueSame(obj) {
return Object.entries(obj).every(([ key, value ]) => {
return key === value;
});
}
console.log(keyValueSame(obj));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/508167.html
標籤:javascript
上一篇:角度布爾輸入字串