【问题标题】:General arrays help needed (returning which arrays share a common value)需要通用数组帮助(返回哪些数组共享一个共同值)
【发布时间】:2021-02-12 11:38:15
【问题描述】:

我已经构建了一些代码来解析命令,然后将它们推送到一个数组中。

每次有新命令通过时,我都想与其他几个包含预定值的数组进行比较,并输出与之匹配的任何可能的数组。

看起来有点像这样:

const collection1 = ['an apple', 'a banana', 'a cherry']
const collection2 = ['a cucumber', 'a pear', 'a banana']
const collection3 = ['a cabbage', 'a cherry', 'an apple']

let fruit
let array[]
case 'banana':
fruit = 'a banana'
break;

array.push(fruit)

我显然有不止一个“案例”,只是保持简单。 我想要做的是,当用户执行一个参数为“banana”的命令时,它会返回包含“banana”的数组。在这种情况下,collection1 和 collection2。

我几天前才开始学习代码,我的第一个项目是这个 Discord 机器人 - 希望你们能指出我正确的方向!

【问题讨论】:

    标签: arrays discord.js


    【解决方案1】:

    您可以使用Array.prototype.filter 仅使用包含特定参数的数组。

    // make an array of the arrays
    const arrays = [
      ['an apple', 'a banana', 'a cherry'],
      ['a cucumber', 'a pear', 'a banana'],
      ['a cabbage', 'a cherry', 'an apple']
    ];
    
    // filter all arrays which doesn't have the element `'a banana'`
    console.log(arrays.filter((arr) => arr.includes('a banana')))

    【讨论】:

    • 还有一件事,假设数组的名称对以后很重要(例如collection1)-我可以在数组中添加某种标签,以便我可以返回“名称”有匹配的数组吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多