【问题标题】:How do you shift an arg twice in Discord.js你如何在 Discord.js 中移动一个 arg 两次
【发布时间】:2020-09-08 10:18:45
【问题描述】:

所以我需要在我的代码中移动 args 两次。这是我到目前为止所拥有的:

const Discord = require('discord.js')
const bot = new Discord.Client()
const token = token here;
const PREFIX = '/';
const embed = new Discord.MessageEmbed()
const ping = require('minecraft-server-util')
bot.on('ready', () => {
  console.log('This bot is online! Created by @littleBitsman.');
})

bot.on('message', message => {
  let args = message.content.substring(PREFIX.length).split(' ')
  if(message.content.startsWith(PREFIX))
  switch (args[0]) {
    case 'ticket':
      if (message.member.roles.highest == '701895573737046066') {
        var usertosendto = args[1]
        var thing = args.shift().shift()
        var embed = new Discord.MessageEmbed()
          .setTitle('Ticket')
          .setDescription('Hey ' + usertosendto + '! You recieved this ticket because of: ' + thing + '.')
          message.channel.send(embed)

      }
  }
})
bot.login(token);

当我执行args.shift().shift() 时,它显示“TypeError: args.shift(...).shift is not a function”。我该怎么办? (我这里取出了一大块代码)

【问题讨论】:

    标签: javascript arrays node.js discord.js


    【解决方案1】:

    Array.prototype.shift() 是一个数组方法。

    shift() 方法从数组中移除第一个元素并返回移除的元素。这个方法改变了数组的长度。

    因此,您最终将第一个元素移出数组。这是从 shift() 返回的。然后,您想再次在 ARRAY 上调用 shift,但您是在返回的元素(数组中的第一个元素)上调用它。

    var thing = args.shift(); // "thing" is now what args[0] was originally ('ticket' in your example).
    // There is no shift() method on a String, so you cannot chain another shift here
    // but you can again reference args to shift from.
    thing = args.shift(); // "thing" is now what args[1] was originally
    

    这里thing 将是数组中的第二项,而 args 数组将短 2 个元素。

    如果你不想缩短数组,你也可以这样做:

    var thing = args[1]; // Note: You have defined args[1] as `usertosendto`, you may be actually trying to work with args[2], the 3rd element in the arguments list.
    

    【讨论】:

    • 这对我不起作用。然后它说“TypeError:thing.shift 不是函数”。
    • 你会注意到在我的任何一个代码示例中都没有说“thing.shift”。 thing.shift(作为字符串的东西)没有 shift 方法,所以这是有道理的。你从数组转移——这里args是你的数组。
    • 它有效,但我发送的字符串只是第一个单词
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2018-07-14
    • 1970-01-01
    • 2010-09-17
    相关资源
    最近更新 更多