简体   繁体   English

如何仅将真值推送到空数组

[英]How to push only true values to an empty array

I have variables assigned to values as:我将变量分配给值:

let x = 5;
let y = 17;
let z = 0;

const newArr = [];

Here I am trying to push the x, y, x values if they aren't falsy values在这里,如果它们不是假值,我将尝试推送x, y, x

I am doing as:我正在做:

if(x){
  newArr.push(x);
}
if(y){
  newArr.push(y);
}
if(z){
  newArr.push(z);
}

May I know more efficient way to do this, TIA我可以知道更有效的方法吗,TIA

You might put all the variables into another array, then filter that array:您可以将所有变量放入另一个数组,然后过滤该数组:

 let x = 5; let y = 17; let z = 0; const newArr = [x, y, z].filter(Boolean); console.log(newArr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM