如果其值为真,则将字符串值添加到数组

假设我有:


const apple = true

const pear = false

const coconut = true

我想拥有:


const activeFruits = ['apple', 'coconut']

我怎么能做这样的事情?这是我试过的:


const activeFruits = [

 apple ? 'apple' : '',

 pear ? 'pear' : '',

 coconut ? 'coconut' : '',

]

然后我必须过滤掉空字符串。


它有效,但对我来说似乎不是最聪明的方法。有没有更好的办法?


翻阅古今
浏览 72回答 3
3回答

蓝山帝景

拥有动态方式的一个想法是拥有一个包含变量的对象:const fruits = {  apple: true,  pear: false,  coconut: true};const activeFruit = Object.keys(fruits).filter(key => !!fruits[key]);console.log(activeFruit)

跃然一笑

不确定这是更聪明还是最聪明,但这是一种不同的方法您可以将所有水果包装到一个对象中,将该对象转换为Object.entries()键值对filter(true使用mapconst apple = trueconst pear = falseconst coconut = trueconst obj = {  apple,  pear,  coconut}const activeFruits = Object.entries(obj)  .filter(([_, value]) => value === true)  .map(([key, _]) => key)console.log(activeFruits)

qq_笑_17

为了回答你的问题,我会这样做:if (apple) {    activeFruits.push('apple');}if (pear) {    activeFruits.push('pear');}if (coconut) {    activeFruits.push('coconut');}但是,我会质疑您拥有的初始数据结构,并(如果可能)将其更改为:const fruits = {    apple: true,    pear: false,    coconut: true};然后得到这样的答案:const activeFruits = Object.keys(fruits).filter(key => !!fruits[key]);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript