我目前正在使用discord.js模块制作机器人。我在JavaScript或编程方面不是很擅长,我试过在任何地方问这个,但我无法解决它。
我的机器人应该从数组中提取图像,其中12张图像保存在我的计算机上。有时它可以成功运行,但有时它只是用“NaN”回复IN DISCORD(不在控制台中)。
else if (msg.content.startsWith(prefix + "duckquery")) {
var ducks = [ {file: "./img/ducks1.jpg"}, {file: "./img/ducks2.jpg"}, {file: "./img/ducks3.jpg"}, +
{file: "./img/ducks4.jpg"}, {file: "./img/ducks5.jpg"}, {file: "./img/ducks6.jpg"}, {file: "./img/ducks7.jpg"}, +
{file: "./img/ducks8.jpg"}, {file: "./img/ducks9.jpg"}, {file: "./img/ducks10.jpg"}, {file: "./img/ducks11.jpg"}, +
{file: "./img/ducks12.jpg"}];
var duck = ducks[Math.floor(Math.random()*(ducks.length))]
msg.channel.send(duck);
答案 0 :(得分:0)
您不应该使用+
,因为那是尝试添加两个对象,为您提供NaN
(非数字)
var ducks = [ {file: "./img/ducks1.jpg"}, {file: "./img/ducks2.jpg"}, {file: "./img/ducks3.jpg"}, +
{file: "./img/ducks4.jpg"}, {file: "./img/ducks5.jpg"}, {file: "./img/ducks6.jpg"}, {file: "./img/ducks7.jpg"}, +
{file: "./img/ducks8.jpg"}, {file: "./img/ducks9.jpg"}, {file: "./img/ducks10.jpg"}, {file: "./img/ducks11.jpg"}, +
{file: "./img/ducks12.jpg"}];
打印出鸭子:
[Object, Object, Object, NaN, Object, Object, Object, NaN, Object, Object, Object, NaN]
改为使用:
var ducks = [
{file: "./img/ducks1.jpg"}, {file: "./img/ducks2.jpg"}, {file: "./img/ducks3.jpg"},
{file: "./img/ducks4.jpg"}, {file: "./img/ducks5.jpg"}, {file: "./img/ducks6.jpg"},
{file: "./img/ducks7.jpg"}, {file: "./img/ducks8.jpg"}, {file: "./img/ducks9.jpg"},
{file: "./img/ducks10.jpg"}, {file: "./img/ducks11.jpg"}, {file: "./img/ducks12.jpg"}
];
它为你提供了对象:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
您确定需要一个对象数组而不是一个字符串数组吗?
var ducks = [
"./img/ducks1.jpg", "./img/ducks2.jpg", "./img/ducks3.jpg",
"./img/ducks4.jpg", "./img/ducks5.jpg", "./img/ducks6.jpg",
"./img/ducks7.jpg", "./img/ducks8.jpg", "./img/ducks9.jpg",
"./img/ducks10.jpg", "./img/ducks11.jpg", "./img/ducks12.jpg"
];