简体   繁体   中英

Why doesn't the console log [Object] instead of my data?

I have a discord bot and I'd like to do a meme command. I store all the memes at a json file memes.json and in my index.js I have a variable for get its data const meme("./memes.json)" and in the embed code I started getting errors, Ill leave my code for you to help me.

const Discord = require("discord.js");

const meme = require("./memes.json")

function RandomNumbers(min, max) {
   return Math.round(Math.random() * (max -  min) + min);
}

client.on("message", function(message) {

const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();

//Other commands
}else if(command === 'meme'){
    const memeNumber = RandomNumbers(1, 6)
    const memeEmbed = new Discord.MessageEmbed()
    .setTitle('Meme')
    .setColor('#0099ff')
    console.log(meme+'.'+memeNumber)
    .setImage(meme+'.'+memeNumber)
    message.channel.send(memeEmbed)
}
//memes.json

{
    "1": "https://images7.memedroid.com/images/UPLOADED762/5e2e4a5a1d35b.jpeg",
    "2": "https://i.pinimg.com/originals/9f/8a/5a/9f8a5afe202b973259d76cbd925660e6.jpg",
    "3": "https://i.redd.it/3bfmb513ihd41.jpg",
    "4": "https://memeplanet.files.wordpress.com/2012/08/kiss-plz.jpg",
    "5": "https://i.kym-cdn.com/photos/images/newsfeed/001/780/926/b82.jpg",
    "6": "https://i.pinimg.com/originals/dd/e2/df/dde2df58419e90f30d3abdcb673717f1.png"
}

I put that console log in there for check what will it give to me, it gave me this

[object Object].2

Combining two strings will not make a functional object property reference. You should be using bracket syntax, as you would for arrays.

console.log(meme[memeNumber])

 const sampleObj = { property: true }; // sample object const propName = 'property'; console.log(sampleObj[propName]); // brackets work fine in general, but also with variables


You should never, ever , do this, but for the sake of being thorough, you could also eval it.

 const sampleObj = { property: true }; const propName = 'property'; eval(`console.log(sampleObj.${propName})`);

This happens because your json is an object and you try to log console.log(meme+'.'+memeNumber) which does this: console.log(meme.toString()+'.'+memeNumber) which {}.toString is [object Object].

You can use console.log() more efectively if you use colon as a separtor (you would not get into these sort of problems), something like: console.log(meme, memeNumber) would print the object stored in meme and the number stored in memeNumber separately.

You can solve your problem by using

console.log(meme[memeNumber])

respectively

.setImage(meme[memeNumber])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM