我正在尝试使用JSON数据库创建一个简单的小型每日奖励系统,以存储奖励和收到它们之前的剩余时间。这是我的代码:
var user = message.author.id;
var userData = JSON.parse(fs.readFileSync('./Toasty/users.json', 'utf8'));
var breadcrumbsRandom = breadcrumbs[Math.floor(Math.random() * breadcrumbs.length)];
var breadRandom = bread[Math.floor(Math.random() * bread.length)];
var toastRandom = toast[Math.floor(Math.random() * toast.length)];
var toastersRandom = toasters[Math.floor(Math.random() * toasters.length)];
message.channel.sendMessage(`**${message.author.username}**, you have received the daily rewards of **${breadcrumbsRandom}** breadcrumbs, **${breadRandom}** slices of bread, **${toastRandom}** pieces of toast and **${toastersRandom}** toasters!`);
var breadcrumbsInt = parseInt(breadcrumbsRandom);
var breadInt = parseInt(breadRandom);
var toastInt = parseInt(toastRandom);
var toastersInt = parseInt(toastersRandom);
if (!userData[user]) userData[user] = {
"breadcrumbs": 0,
"bread": 0,
"toast": 0,
"toasters": 0
};
console.log(userData[user].breadcrumbs);
console.log(breadcrumbsInt);
userData[user].breadcrumbs = userData[user].breadcrumbs + breadcrumbsInt;
userData[user].bread = userData[user].bread + breadInt;
userData[user].toast = userData[user].toast + toastInt;
userData[user].toasters = userData[user].toasters + toastersInt;
var updateRewards = JSON.stringify(userData, null, 2);
fs.writeFile('./Toasty/users.json', updateRewards);
问题是当我记录它时,userData [user] .breadcrumbs是未定义的,因此如果我记录了这些值,那么.bread .toast和.toasters就是这样。我不明白为什么它没有定义。另外,当使用writeFile并且我检查.json文件有什么时,它会对面包屑,面包,烤面包和烤面包机值显示为null。提前感谢您的帮助和时间!