首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何更改对象中的值,但仍保留某些值?

如何更改对象中的值,但仍保留某些值?
EN

Stack Overflow用户
提问于 2022-08-06 02:14:56
回答 1查看 47关注 0票数 0

我正在尝试创建一个练习和创建一个函数,在这个函数中,如果计数与该价格匹配,或者是打开初始价格的一半,并且如果计数下降到0,也不会重置为false。

以下是一些示例数据:

代码语言:javascript
复制
openData = {
    count: 0,
    chest: [
      { id: 'Chest1', price: 50, open: false },
      { id: 'Chest2', price: 200, open: false },
      { id: 'Chest3', price: 500, open: false }
    ]
  };

("changes `open` to `true` when the count is equal to or larger than half the initial price of the id", function() {
  openData.count = 100;
  code.unlockedChest(openData.chest, openData.count);
  expect(openData.chest[0].open).to.equal(true);
  expect(openData.chest[1].open).to.equal(true);
  expect(openData.chest[2].open).to.equal(false);
});

('does not set `open` to `false` once a chest has been opened, even if the count drops again', function() {
  openData.count = 100;
  code.unlockedChest(openData.chest, openData.count);
  openData.count = 0;
  code.unlockedChest(openData.chest, openData.count);
  expect(openData.chest[0].open).to.equal(true);
  expect(openData.chest[1].open).to.equal(true);
  expect(openData.chest[2].open).to.equal(false);
});

});

以下是我到目前为止的想法:

代码语言:javascript
复制
function unlockedChest (id, count) {
    if (count === chest.price || count <= chest.price) {
      return chest.open === true;
    } 
    if (chest.open === true) {
      return true; // trying to keep the value that it was changed to
    }

}

我已经试着玩了几个小时了,我不认为我的逻辑也是正确的,因为让我失望的是‘一半’的措辞,我正在得到的输出结果对于第一个规范来说是假的。

我也想知道这是否是一种使用循环的情况?

任何额外的指导将在这两个规格将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2022-08-06 02:25:21

如果我正确地理解了您,您希望根据chest.open的值更新chest.price的值,但前提是胸部尚未打开(chest.open不是真)。

在执行任何其他逻辑之前,您可以通过检查开放条件来实现这一点。如果是chest.open == true,那么就没有必要检查价格,至少不需要作为更新chest.open的函数的一部分。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73256731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档