简体   繁体   English

在一行中按条件将项目推送到数组

[英]Push item onto array on condition in one line

I want something like this and I would like to know if this is possible in JavaScript in one line, or I have to write an if statement我想要这样的东西,我想知道这在 JavaScript 中是否可行,或者我必须写一个 if 语句

// these versions adds fasle to the array if condition = false let arr = await getArray(params).push(condition && itemToAdd); arr = await getArray(params).push((() => condition && itemToAdd)()); // this version adds undefined to the array if condition = false arr = await getArray(params).push((() => { if (condition) return itemToAdd })());

(the reason I included the getArray part is cuz that's how it looks in my code and I don't actually save this array to a var arr only its being returned right away to its calling function, so that's why I don't want to add a line for the if statement...) (我包含 getArray 部分的原因是因为这就是它在我的代码中的样子,我实际上并没有将此数组保存到 var arr中,只是它立即返回到它的调用 function,所以这就是我不想为 if 语句添加一行...)

Not sure why you want to do it in a single line, but this can work不知道为什么要在一行中完成,但这可以工作

let arr = [...await getArray(), itemToAdd].slice(0, condition? undefined: -1);

Here we are pushing the itemToAdd in the array regardless of the condition, but we remove the last element ( itemToAdd ) if the condition is false.在这里,无论条件如何,我们都将itemToAdd推送到数组中,但如果条件为假,我们将删除最后一个元素 ( itemToAdd )。

if you are working with reactjs then you can use useState for conditions如果您正在使用 reactjs 那么您可以使用 useState 作为条件

const [isCondition, setisCondition] = useState(false);

//but you need if/else to change useState //但是你需要 if/else 来改变 useState

 if(this_happens) {

setisCondition(true) } else { setisCondition(false) }设置条件(真)}否则{设置条件(假)}

//you can do it as like //你可以这样做

let arr = await getArray(params).push(isCondition && itemToAdd);

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

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