G
G
gohellp2021-04-08 23:37:02
Node.js
gohellp, 2021-04-08 23:37:02

Where does it get the new array element from and where does it put the values?

I decided to do a friend's task, in a language convenient for myself, and so as not to once again call the survey from the console, I decided to do it through the discord.
The task was like this:

Enter n integers(>0 or <0). Find the difference of numbers. Display the result on the screen.


I wrote code for this:
const Discord = require('discord.js');
const bot = new Discord.Client();
const {token1} = require('./conf.json');
var mas =[]
var prom =[]
let a
let i=1

bot.on("message", msg => {
    msg.content = msg.content.toLowerCase().split(" ")
    switch (msg.content[0]) {
        case"!add":
            if (!msg.author.bot){
                if (!msg.content[2]) {
                    msg.reply("Введите, хотя бы 2 значения!")
                } else {
                    mas=[]
                    for (let i = 1; msg.content[i]; i++) {
                        mas.push(Number(msg.content[i]))
                    }
                    msg.reply("Готово. Можете вводить !math")
                    a = mas.length + 1
                }
            }
        break;
        case"!math":
            try{
                prom = []
                mas.push(0)
                while(i<mas.length){
                    mas[a] = mas[i-1] - mas[i];
                    prom.push(mas[a])
                    i++
                }
                console.log(mas)
                console.log(prom)
                msg.reply("Результат: " + mas[a-1] + "\nПромежуточные результаты: " + prom)
                mas = []
            }catch (e) {
                msg.reply("Сначала введите значения!!!")
            }
        break;
    }
})

bot.login(token1);


But instead of working normally, it decides to prove itself:
zuwem2R.png
PvTRIvg.png

1) It did not write the intermediate result to prom
2) It took another array element from somewhere and refused to count
3) It simply refused to count

I want to understand by what principle this additional element arises and in general how cleanly this task is performed.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
StiflerProger, 2021-04-09
@gohellp

bot.on("message", msg => {

  let [type, ...data] = msg.content.toLowerCase().split(" ");

  if (msg.author.bot) return; // игнорируем бота

  switch (type) {
    case "!add":
      if (data.length < 2) return msg.reply("Введите, хотя бы 2 значения!");

      if (data.find(e => isNaN(e) || Number(e) === 0 || Math.floor(e) !== Number(e))) {
        return msg.reply("Числа должны быть целыми в диапазоне (-∞, 0), (0, ∞)");
      }

      msg.reply("Результат: " + data.slice(1).reduce((acc, cur, index) => acc - cur, data[0]));
      break;

    default:
      msg.reply("Чтобы вычислить разницу чисел. Вызовите команду !add <числа через пробел>");
      break;
  }

})

For the task at hand, your code is too confusing. You don’t need to save intermediate results anywhere, and you don’t need to ask the user to enter ! math

L
low molecular macro, 2021-04-09
@molekulyarniy

let msg = "!add 45 15 30"

let prom = [];
let result = 0;


let message = msg.toLowerCase().split(" ");

if(message[0] == "!add") {
    prom = [];
    result = 0;
    
    if(message.length < 3) {
        console.log('Введите хотя бы 2 значения!');
    }
    else {
        for(let i=1; i<message.length; i++) {
            result += Number(message[i])
            prom.push(result)
        }
        console.log('Готово! Можете вводить !math')
        console.log(prom)
        console.log(result)
    }
}
if(message[0] == "!math") {
    console.log(prom)
    console.log(result)
}

adjust for yourself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question