2017-07-18 19 views

回答

1

你可以提取到邏輯的方法和使用對象,這類似於您最初的代碼:

const getValue = key => { 
    return { 
    foo: 'bar', 
    bar: 'baz', 
    baz: 'quux', 
    }[key] || 'defaultValue' 
} 

const someVar = getValue(otherVar) 

這可以進一步簡化,但不管是更具可讀性是值得商榷的

const getValue = key => ({ 
    foo: 'bar', 
    bar: 'baz', 
    baz: 'quux', 
}[key] || 'defaultValue') 

const someVar = getValue(otherValue) 

您仍然可以立即如果你調用該函數但是通過將邏輯提取到一個方法中,它可以在其他地方使用並簡化測試。

0

使用三元運算符的解決方案。

const someVar = ((otherVar) => { 
 
    return (otherVar == "someVal")? "something": (otherVar == "otherVal")? "somethingElse": "somethingDefault"; 
 

 
})("someVal") 
 

 
console.log(someVar);

相關問題