[英]How to shorten multiple if statements (not if else)
I have an array in which i want to conditionally push some values.我有一个数组,我想有条件地推送一些值。 Is there a cleaner way of doing this (code below)?
有没有更清洁的方法(下面的代码)?
const pushedValues = [];
if (someArray[0].value) {
pushedValues.push(x);
}
if (someArray[1].value) {
pushedValues.push(y);
}
if (someArray[2].value) {
pushedValues.push(z);
}
...
You can put the values x, y, z
into an array and loop over the values with the index.您可以将值
x, y, z
放入一个数组中,并使用索引遍历这些值。
const pushedValues = [];
[x, y, z].forEach((val, i)=>{
if(someArray[i].value) pushedValues.push(val);
});
you can use a forEach like this你可以像这样使用 forEach
const pushedValues = [];
const data = [x, y, z]
someArray.forEach((v, i) => {
v.value && pushedValues.push(data[i])
})
You are working with the someArray
array.您正在使用
someArray
数组。 You must first check the values inside an iterative control ( for
or while
) and then use the switch-case
construct.您必须首先检查迭代控件(
for
或while
)中的值,然后使用switch-case
构造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.