首页 > 解决方案 > 如何将 JSON 文件中的数字递减到 0?

问题描述

我有一个 JSON 文件,它为特定工作人员设置了静音,我想将其递减到 0,我该怎么做?

我也想要一个代码来减少所有工作人员的静音

client.on('message', message => {

  if(!staffstats[message.author.id]) staffstats[message.author.id] = {
    mutes: 0,
    bans: 0,
    warns: 0,
    tickets: 0,
    appeals: 0,
    vips: 0,
    WarnedTimes: 0
  }

  if(message.content === prefix + "mutes-reset"){
    user = message.mentions.users.first();

    staffstats[user.id].mutes--;
  }
})

标签: discord.js

解决方案


你很亲近!您可以这样做staffstats[user.id].mutes = staffstats[user.id].mutes - 1;,但是,您确实要求直到 0,因此在更改值之前进行简单检查就足够了:

if (!staffstats[user.id].mutes <= 0) //if mutes value is NOT lower or equal to 0, do:
  staffstats[user.id].mutes = staffstats[user.id].mutes - 1; //reduces current value of mutes by 1

decrement all staff members mutes,您需要知道员工是谁,以及他们的 ID。假设您知道这一点,例如,您可以遍历用户 ID 数组。

如果您仅将所有员工的所有值存储在对象 ( {}) 中,那么您可以Object.keys(staffstats);为所有键(这些是用户 ID)执行操作,因为它方便地存储在一个可以循环的数组中。

var staffId = ['12345', '23456', '34567']; //this is just an example array
staffId.forEach(id => { //loop through array of staffId, storing value in id variable
  //same method as above
  if (!staffstats[id].mutes <= 0)
    staffstats[id].mutes = staffstats[id].mutes - 1;
};

推荐阅读