首页 > 解决方案 > 我将一个变量声明为 '',然后在 https.get() 语句中对其进行编辑。当我之后尝试记录它时,它仍然显示为''

问题描述

当我在 https.get() 语句中编辑变量并记录它时,它会正常工作。当我尝试在外面记录它时,就好像它根本没有被编辑过。有没有办法防止这种情况发生?

const https = require('https');

//The data object is a JSON file that is gotten from an api. It has a GuildMembers array which contains an expHistory object, which requires a ton of formatting to get the numbers from the object.
data = JSON.parse(data)
let guildMembers = data.guild.members
let output = ''
for (let i=0; i<guildMembers.length; i++) {
    let weeklyXP = JSON.stringify(guildMembers[i].expHistory)
    //this part removes some unnecessary characters from the expHistory
    for (let x=1;x<=14;x++) {
      weeklyXP = weeklyXP.replace('"', '')
    }
    let weeklyXPArray = weeklyXP.split(',')
    let XPArray = [weeklyXPArray[0].split(':')[1], weeklyXPArray[1].split(':')[1], weeklyXPArray[2].split(':')[1], weeklyXPArray[3].split(':')[1], weeklyXPArray[4].split(':')[1], weeklyXPArray[5].split(':')[1], weeklyXPArray[6].split(':')[1].replace('}', '')]
    //After the formatting above, this part adds all the expHistory, turns it into a number and adds it to 'total'.
    let total = 0
    for (let y=0; y<XPArray.length;y++) {
      total += parseFloat(XPArray[y], 10)
    }
    //this is the https.get() to another api, it is run to get each user in the guildMember array's username using an api.
    https.get(`https://api.mojang.com/user/profiles/${guildMembers[i].uuid}/names`, (resp) => {
        let mojangData = ''
                                                    
        resp.on('data', (chunk) => {
        mojangData  += chunk
        })
        resp.on('end', () => {
        mojangData = JSON.parse(mojangData)
        let playerUsername = mojangData[mojangData.length - 1]
        //The 'format' variable is a string that is used to add all the information to 'output'
        const format = `\n${playerUsername.name} with ${total} GEXP`
        output += format
        })
        while (output !== '') {
            console.log('x') //returns infinite 'x's
        }
    })
    while (output !== '') {
        console.log('y') //returns no y's
    }
}
//this is where I am trying to send 'output'

标签: javascriptstring

解决方案


我想你忘了逃避双引号。尝试使用 \" 而不是 "


推荐阅读