创建保险箱的简单实现,并提供插入和移除物品的方法,同时跟踪保险箱的容量

问题描述 投票:0回答:2

我收到以下代码的预期错误。

',' 预计。 ide 指向函数remove 的右大括号,即最后一个大括号之前的大括号

浏览器控制台错误:未捕获的语法错误:参数列表后缺少 )

我想要实现的目标:

编写一个remove方法,从存储中删除指定的项,并返回删除的项,如果没有找到 返回字符串 Not Found,如果有多个同名项目,则返回找到的第一个。

class Safe {
  constructor(safeSize) {
    this.storage = [];
    this.safeSize = safeSize;
  }
  insert(name, size) {

    if (this.safeSize - size >= 0) {
      this.safeSize -= size;
      this.storage.push({
        name: size
      }); // push it as an object
      return true;
    }
    return false;
  }

  remove(test) {
    let shouldSkip = false;
    this.storage.forEach(function(element, index) {

        if (shouldSkip) {
          return;
        }

        if (element === test) {
          shouldSkip = true;
          const removedItem = element;
          this.storage.pop(element);
          return ("The item" + removedItem + " Has been removed");
        }
        return (test + "  Item not found");
      }
    }
  }
> test cases:
>
> safe.insert("watermelon", 7);  => true 
> safe.insert("plate", 2);       => true
>
> safe.remove("money");           => "Not Found" 
> safe.remove("watermelon");      => {name: "watermelon", "size: 7"} 
> safe.remove("watermelon");      => "Not Found"
javascript class
2个回答
1
投票

您的代码中有一些错误的代码。 请使用此代码。

class Safe {
  constructor(safeSize) {
    this.storage = [];
    this.safeSize = safeSize;
  }
  insert(name, size) {

    if (this.safeSize - size >= 0) {
      this.safeSize -= size;
      this.storage.push({
        name, size
      }); // push it as an object
      return true;
    }
    return false;
  }

  remove(test) {
    let shouldSkip = false;
    let message = "";
    this.storage = this.storage.filter( element => {
        if(element.name == test && !shouldSkip) {
            shouldSkip = true;
            message = "The item " + element.name + " Has been removed"
            return false;
        }
        return true;
    });
    if(!shouldSkip) message = test + " Item not found";
    return message;
  }
}

-1
投票

您缺少 forEach 函数的右括号:

  remove(test) {
    let shouldSkip = false;
    this.storage.forEach(function(element, index) {

        if (shouldSkip) {
          return;
        }

        if (element === test) {
          shouldSkip = true;
          const removedItem = element;
          this.storage.pop(element);
          return ("The item" + removedItem + " Has been removed");
        }
        return (test + "  Item not found");
    }) //<------
  }
© www.soinside.com 2019 - 2024. All rights reserved.