我有一個條件陣列
let conditions = [1, 3,5,7,9】。]
let values = [1,2,3, 4, 5,6,7,8,9, >0]
我想
if (values == 1 || values==3 || values == 5 || values == 7 || values == 9 ){
return values * 3
} else {
return值 * 2
誰能幫助避免寫多個OR條件,并在1個陳述句中完成這個任務? 謝謝你
uj5u.com熱心網友回復:
首先:你可以使用map運算子來遍歷你的值
然后通過includes檢查
let conditions = [1, 3,5,7,9】。]
let values = [1,2,3, 4, 5,6,7,8,9, >0]
const result = values.map(val => conditions。 includes(val) ? val * 3 : val * 2)。)
console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
我建議從你的條件中創建一個Set,這對大資料集來說會更有效率。然后你可以使用Array.map()來創建你的結果。
let conditions = new Set([1, 3,5,7,9] )。)
let values = [1,2,3, 4, 5,6,7,8,9, >0]
function getResult(values, conditions){
return values.map(value => conditions. has(value) ? value * 3: value * 2)
}
console.log('getResult:', getResult(values, conditions));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你可以這樣做:
const toAvoidArray = [1, 3, 5, 7, 9]
if (toAvoidArray.indexOf(value)!== -1) {
return values * 3.
} else {
return值 * 2
或者在你的情況下,你可以這樣做:
if (value%2! ==0) {
return values * 3.
} else {
return值 * 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/314473.html
標籤:
