[英]How to shorten multiple if statements (not if else)
我有一個數組,我想有條件地推送一些值。 有沒有更清潔的方法(下面的代碼)?
const pushedValues = [];
if (someArray[0].value) {
pushedValues.push(x);
}
if (someArray[1].value) {
pushedValues.push(y);
}
if (someArray[2].value) {
pushedValues.push(z);
}
...
您可以將值x, y, z
放入一個數組中,並使用索引遍歷這些值。
const pushedValues = [];
[x, y, z].forEach((val, i)=>{
if(someArray[i].value) pushedValues.push(val);
});
你可以像這樣使用 forEach
const pushedValues = [];
const data = [x, y, z]
someArray.forEach((v, i) => {
v.value && pushedValues.push(data[i])
})
您正在使用someArray
數組。 您必須首先檢查迭代控件( for
或while
)中的值,然后使用switch-case
構造。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.