提问者:小点点

如何检查一个数组是否有一些整数,然后将它们全部相加得到一个结果


const Discord = require('discord.js');
const bot2 = new Discord.Client();


const mark = '*interesting';
const marker = '*reverse'
const markir = '*fakereverse'
const markri = '*falsereverse'
const markre = '*randomise_'
const mrk = '*replace_'
const markro ='*math'
let para_meter = false
function reverseString(str) {
   return str.split("").reverse().join("");
}
function randomise(str) {
   randomnumber = Math.floor(Math.random() * str.length)
   strarr = str.split('')
   alphabet = ['A', 'a', 'B','b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z']
   alpharandom = alphabet[Math.floor(Math.random() * 52)]
   strarr[randomnumber] = alpharandom
   return strarr.join('')
}

bot2.on('message', msg =>{
   
   let args = msg.content.substring(mark.length)
   let sgra = msg.content.substring(marker.length)
   let thisis = msg.content.substring(markir.length)
   let sisiht = msg.content.substring(markri.length)
   let argon = msg.content.substring(markre.length)   
   let goodgood = msg.content.substring(mrk.length)
   let spited = msg.content.split(' ')
   
   if(msg.content.startsWith(mark)){
      let thee = args + ". I'm not dad. I'm bad discord bot"
      msg.channel.send(thee)
   }
   if(msg.content.startsWith(marker)){
      if(sgra == ''){
         msg.channel.send('you need something to reverse')
         return
      }
      let arg = reverseString(sgra)
      msg.channel.send(arg)
   }
   if(msg.content.startsWith(markir)){
      if(thisis == ''){
         msg.channel.send('you need something to fakereverse')
         return
      }
      let tese = thisis.split(' ')
      let arrayI = []
      tese.forEach(thing => {
         arrayI.push(reverseString(thing))
      })
      msg.channel.send(arrayI.join(' '))
      
   }
   if(msg.content.startsWith(markri)){
      if(sisiht == ''){
         msg.channel.send('you need something to falsereverse')
         return
      }
      let eset = sisiht.split(' ')
      let arrayII = []
      eset.forEach(gniht => {
         arrayII.push(reverseString(gniht))
      })
      let somethingi = arrayII.join(' ')
      msg.channel.send(reverseString(somethingi))
   }
   if(msg.content.startsWith(markre)){
      if(argon == ''){
         msg.channel.send('you need something to randomise')
         return
      }
      let esci = argon.split(' ')
      let arrayIII = []
      esci.forEach(thing => {
         let thingo = randomise(thing)
         arrayIII.push(thingo)
      })
      msg.channel.send(arrayIII.join(' '))
   }
   if(msg.content.startsWith(mrk)){
      if(goodgood == ''){
         msg.channel.send('you need some words to replace')
         return
      }
      let doog = goodgood.split(' ')
      let arrayIV = []
      doog.forEach(item => {
         switch(item.length){
            case 0:
               arrayIV.push(' ')
               break;
            case 1:
               arrayIV.push('a')
               break;
            case 2:
               arrayIV.push('an')
               break;
            case 3:
               arrayIV.push('the')
               break;
            case 4:
               arrayIV.push('what')
               break;
            case 5:
               arrayIV.push('where')
               break;
            case 6:
               arrayIV.push('flight')
               break;
            case 7:
               arrayIV.push('amazing')
               break;
            case 8:
               arrayIV.push('censored')
               break;
            case 9:
               arrayIV.push('wordcount')
               break;
            case 10:
               arrayIV.push('everything')
               break;
            case 11:
               arrayIV.push('magnificent')
               break;
            case 12:
               arrayIV.push('mitochondria')
               break;
            case 13:
               arrayIV.push('unlucky_number')
               break;
            default:
               fakearray = ['\nAccording to all known laws', 'of aviation,', '', '', 'there is no way a bee', 'should be able to fly.', '', '','Its wings are too small to get','its fat little body off the ground.', '', '',`because bees don't care`,'what humans think is impossible.\n'  ]
               fakestring = fakearray.join('\n')
               arrayIV.push(fakestring)
               break;
         }
      

      })
      msg.channel.send(arrayIV.join(' '))
   }
   if(spited[0] == markro){
      if(!spited[1]){
         msg.reply('there needs to be a math function to use')
         return;
      }
      switch (spited[1]) {
         case 'add':
            if(!spited[2]){
               msg.reply('you need something to add') 
            } else {
               let thestuff = msg.content.split(' ').splice(markro, 1).splice('add', 1)
               thestuff.forEach(elem => {
                  if(!isNaN(elem)){
                     para_meter = true
                  }
               })
               if(para_meter == true){
                  msg.reply('these are not integers')
                  para_meter = false
                  return;
               }
               var reduced = 0
               thestuff.forEach(eleme => {
                  reduced += eleme
               })
               msg.channel.send(reduced)

            }

            break;
      
         default:
            break;
      }

   }
   
   
  

  
})
 


bot2.login(process.env.token2)

把注意力集中在最后一个命令上。 这就是我的问题所在。 在它中,我尝试检测消息的开头是否有*math add。 然后,我尝试检查消息是否包含非整数字(通过将消息转换为数组),然后尝试将它们相加(如果所有的字都是整数),并得到一个结果,可以作为消息发送。 下面是有问题的命令

 if(spited[0] == markro){
      if(!spited[1]){
         msg.reply('there needs to be a math function to use')
         return;
      }
      switch (spited[1]) {
         case 'add':
            if(!spited[2]){
               msg.reply('you need something to add') 
            } else {
               let thestuff = msg.content.split(' ').splice(markro, 1).slice('add', 1)
               thestuff.forEach(elem => {
                  if(!isNaN(elem)){
                     para_meter = true
                  }
               })
               if(para_meter == true){
                  msg.reply('these are not integers')
                  para_meter = false
                  return;
               }
               var reduced = 0
               thestuff.forEach(eleme => {
                  reduced += eleme
               })
               msg.channel.send(reduced)

            }

            break;
      
         default:
            break;
      }

   }

每当我实际尝试使用它时,通过bots命令,它只会响应'0*math)。 我该如何解决这个问题

(我很感激长代码是可滚动的,而且不在一个块中)


共1个答案

匿名用户

如果要将数组中的所有数字相加,可以使用reduce来完成。 只需在添加之前检查类型即可。

像这样的东西应该能奏效。

null

// ~ Original ~
//  * Numbers are typed as such (not strings)
/** const myArray = [{}, [], "a", 1, "b", 3, "c", 5]; **/

// ~ Updated ~
//  * Numbers are in string form (same as you are 
//    receiving the data from the API)
const myArray = [{}, [], "a", "1", "b", "3", "c", "5"]; 

const result = addNumbers(myArray); 

console.log(result); // 9

function addNumbers (arr = []) {
  if (!Array.isArray(arr)) {
    throw new Error(
      `[addNumbers] Parameter type is '${typeof arr}', need Array!`
    );
  }
  
  return arr.reduce((a, v) => 
    (isNaN(Number.parseInt(v)) ? 0 : Number(v)) + a, 0);
}