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


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。然后我尝试检查消息是否具有非整数单词(通过将消息转换为数组(,然后我尝试(如果所有单词都是整数(将它们相加并获得可以作为消息发送的结果。这是有问题的命令

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;
}
}

每当我实际尝试使用它时,尽管机器人命令它只是以"0*math"响应。我该如何解决这个问题

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

请参阅此答案底部的更新

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

这样的东西应该可以解决问题。

原答案:

// ~ 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);
}

<小时 /> <小时 />

更新1

从整体上重新思考当前的解决方案

据我所知,无论是加法、乘法等,您都期待一个特定的字符串。这意味着不需要遍历数组。

例:

// Set default value for input/query 
setQuery("add");
/**
* parseInput is our main function that parses "chat" commands
*/
function parseInput(inputStr) {
// Replace multiple spaces with single space
// In case someone types '*math     add      3        3' or something
const inputStrSingleSpaced = inputStr.replace(/ss+/g, " ");
// Turn our string into an array
const inputArr = inputStrSingleSpaced.split(" ");
// Our array should contain 4 elements regardless of operation (add/multiply/etc)
if (inputArr.length !== 4) return undefined; // Could throw an error here?
const firstNum = Number(inputArr[2]); // First number should always be 3rd element in array
const secondNum = Number(inputArr[3]); // You get the idea..
const operation = inputArr[1];
switch (operation) {
case "add": return firstNum + secondNum;
case "multiply": return firstNum * secondNum;
// case "subtract": ...etc
default: return undefined; // Throw an error if you want instead?
}
}

/**
* sendIt "sends" our chat/query string for parsing
*/
function sendIt() {
const el = document.querySelector("#textbox");
const resEl = document.querySelector("#results");
const calculation = parseInput(el.value);
resEl.innerHTML = `<h1>Result: ${calculation}</h1>`;
}

/**
* setQuery lets us set the input value to a demo query string
*/
function setQuery(kind) {
const el = document.querySelector("#textbox");
if (kind === "add") el.value = `*math add ${rando()} ${rando()}`;
if (kind === "add_with_spaces") el.value = `*math    add        ${rando()}       ${rando()}`;
if (kind === "multiply") el.value = `*math multiply ${rando()} ${rando()}`;
}
/**
* rando returns a random number between 0 and 50
*/
function rando() {
return Math.floor(Math.random() * 50);
}
.mt20 {
margin-top: 20px;
}
<h3>Enter query string (simulating chatting) then hit 'Send'</h3>
<input type="text" id="textbox" />
<button onclick="sendIt()">Send</button>
<hr />
<div id="results" class="mt20"></div>
<hr />
<div class="mt20">
Example Queries: <small><i>Click one to set query</i></small>
<br />
<button onclick="setQuery('add')">Add</button>
<button onclick="setQuery('multiply')">Multiply</button>
<button onclick="setQuery('add_with_spaces')">Multiple Spaces</button>
</div>

<小时 /> <小时 />

更新2:

如果要镜像addNumbers函数,但要进行乘法:

const myArray = [{}, [], "a", "9", "b", "3", "c"]; 
const result = multiplyNumbers(myArray); 
console.log(result); // 27
function multiplyNumbers (arr = []) {
if (!Array.isArray(arr)) {
throw new Error(
`[multiplyNumbers] Parameter type is '${typeof arr}', need Array!`
);
}

return arr.reduce((a, v) => {
if (!isNaN(Number.parseInt(v))) { // If we are able to parse the string into an int
if (a === 0) return Number(v); // If accumulator is 0, just return current value (don't want to multiply by 0)
return Number(v) * Number(a); // If accumulator is NOT 0, multiply
}
return Number(a);
}, 0);
}

最新更新