如果我不知道变量会有多长,如何限制变量以接受字符串中的特定值?



我正在尝试创建变量,以接受我正在尝试制作的discord 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接收到要静音的成员的参数时,它也会接收到时间框架和时间,时间会随着时间的推移而变化。如果我不知道每个值的长度,我怎么能限制mutee只接受mutee,时间只接受时间?

如果您计划在以后使用类似的命令,您可能需要考虑实现Arguments。不过,我会给你举一个简单的例子。


这样看:您的消息内容看起来像这样:

!mute @User 10m Spam

我们如何知道什么是什么?间距。

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

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

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

但是如果原因大于1个单词,则会将原因分解为多个部分。我马上就到。

首先,让我们将mutee和时间分开

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(' ');

最新更新