简体   繁体   English

如何设置条件以从 Javascript object 中删除属性?

[英]How do I set a condition to remove a property from Javascript object?

Im trying to remove the level_6 if counter,== maxCount.如果计数器,== maxCount,我试图删除 level_6。 but it removes the level_6 on both "if" and "else".但它删除了“if”和“else”上的 level_6。

let maxCount = 5;
let counter = 1;

this.combinations = {
  level_1: [ [0] ],
  level_2: [ [0] ],
  level_3: [ [0] ],
  level_4: [ [0] ],
  level_5: [ [0] ],
  level_6: [ [0] ]
};

app.post("/get-level", CSRFHeaderSecurity.Init, (req, res) => {
  let level = req.body.level;

  if (level === 1) {
    if (counter === maxCount) {
      counter = 1;
    } else {
      counter++;
    }
    storage.setItem("counter", counter).then(() => {
      console.log(counter);
    });
  }

  if (counter === maxCount) {
    res.send(
      JSON.stringify({
        level: this.combinations[`level_${level}`]
      })
    );
  } else {
    delete this.combinations.level_6;
    res.send(
      JSON.stringify({
        level: this.combinations[`level_${level}`]
      })
    );
  }
});

I expect to get 5 combinations/levels if the counter is equal to 5, but if the counter is not equal to 5 i want the combonations/levels to remain 6如果计数器等于 5,我希望获得 5 个组合/级别,但如果计数器不等于 5,我希望组合/级别保持 6

Your logic has an issue.你的逻辑有问题。 level_6 get's deleted on level_1 if the counter reached the value of maxCount .如果计数器达到 maxCount 的值,则在 level_1 上删除maxCount This code block is the culprit:这个代码块是罪魁祸首:

if (level === 1) {
if (counter === maxCount) {
  counter = 1;
} else {
  counter++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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