【问题标题】:How can I limit variables to take in specific values in a string, if I don't know how long the values will be?如果我不知道值的长度,如何限制变量以获取字符串中的特定值?
【发布时间】:2021-08-10 20:09:39
【问题描述】:

我正在尝试创建变量以接受我尝试创建的不和谐静音命令的参数。我尝试制作三个变量,静音、时间和原因。 该命令旨在采用这种格式 !mute [静音,时间,原因]。

const mutee = JSON.parse(message.content.slice(7));
//gets the member u want to mute
const time = JSON.parse(message.content.slice(8 + mutee.length()));
//gets the time you want the user to be muted for
const reason = JSON.parse(message.content.slice(9 + mutee.length() + time.length()));
//gets the reason for the mute

当变量 mutee 为打算被静音的成员接收参数时,它也将考虑时间范围,而 reason 和 time 将与时间一起考虑。如果我不知道这些值中的每一个会持续多长时间,我该如何限制 mutee 只接受 mutee 和 time 只接受 time?

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    如果您打算使用类似的命令,您可能需要考虑实现Arguments。不过,我将向您展示一个简单的示例。


    这样看: 您的消息内容如下所示:

    !mute @User 10m Spam
    

    我们怎么知道什么是什么?间距。

    [!mute ... @User ... 10m ... Spam]
    

    我们可以用空格分割消息,给我们一个子字符串数组,每个子字符串都是单独的单词

    const words = message.content.split(' ');
    // words => ['!mute', '@User', '10m', 'Spam'];
    

    但是,如果超过 1 个单词,这会将原因分成多个部分。我马上就会讲到。

    首先让我们将静音和时间分开

    const words = message.content.split(' ');
    const mutee = words[1]; // '@User'
    const time = words[2]; // '10m'
    

    我们可以使用.join() 将数组的其余部分分配给一个变量。这将自动将所有子字符串连接成一个字符串作为原因。

    // Slice will remove the first 2 elements which we known to be the mutee and time
    
    const reason = words.slice(3).join(' '); 
    // reason => 'Spam' ... And anything in front!
    

    您的最终代码将如下所示

    const words = message.content.split(' ');
    const mutee = words[1];
    const time = words[2];
    const reason = words.slice(3).join(' ');
    

    在 ES6 中,你可以通过一些语法糖来做到这一点。

    const words = message.content.split(' ');
    let [, mutee, time, ...reason] = words;
    reason = reason.join(' ');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多