编码挑战,努力找出如何从方法中返回字符串

时间:2019-02-23 01:00:59

标签: javascript

我正在解决代码挑战,如果在attemptAnswer(guess)中传递的猜测与answer属性的值匹配,则需要将字符串返回到变量中。我的测试当前失败,原因是变量response未定义。

这是某种有约束力的问题吗?

...好奇如何解决此问题。

谢谢!

class Sphinx {
    constructor() {
        this.name = null;
        this.riddles = [];
    }
    collectRiddle(riddle) {
        this.riddles.push(riddle);
        if (this.riddles.length > 3) { this.riddles.shift() };
    }
    attemptAnswer(guess) {
        this.riddles.forEach( (element, index) => {
            if (guess === element.answer) { 
                this.riddles.splice(index, 1);
                return "That wasn't that hard, I bet you don't get the next one."
            };
        })
    }
}

//test
 const response = sphinx.attemptAnswer('short');
 assert.equal(response, 'That wasn\'t that hard, I bet you don\'t get the next one');

3 个答案:

答案 0 :(得分:0)

当您返回attemptAnswer()时,实际上是在重新调整到定义的内部forEach回调函数:(element, index) => {...,而不是外部的attemptAnswer()方法。

您可以在此循环外设置一个名为forEach的变量,而不是立即在您的result循环中返回,然后在result循环完成后返回forEach

此外,当前,您还没有创建Sphinx的新实例,这意味着您没有可以调用attemptAnswer()方法的对象。要解决此问题,请添加new Sphinx()以创建一个新的Sphinx对象。

请参见以下示例:

class Sphinx {
  constructor() {
    this.name = null;
    this.riddles = [{"answer":"short"}];
  }
  collectRiddle(riddle) {
    this.riddles.push(riddle);
    if (this.riddles.length > 3) {
      this.riddles.shift()
    };
  }
  attemptAnswer(guess) {
    let res = "";
    this.riddles.forEach((element, index) => {
      if (guess === element.answer && !res) { 
        // no need for splice as it will skip an entry
        res = "That wasn't that hard, I bet you don't get the next one.";
      };
    })
    return res;
  }
}


const response = new Sphinx();
response.collectRiddle({"answer":"short"});
console.log(response.attemptAnswer('short'));

答案 1 :(得分:0)

您永远不会调用MongoDB Compass,因此{"_id":"Deadpool","Path":"path/to/file"} 始终为collectRiddle,并且永远不会输入this.riddles块,因此,不返回任何内容,因此返回值为[]

在循环之前,您应该有一个名为forEach的变量,如果找到匹配项,请将其设置为undefined,然后根据found变量返回字符串:

注意:函数内部的字符串与您要比较的字符串不同(它带有反斜杠,并以点结尾),因此测试始终是虚假的

true

答案 2 :(得分:0)

我假设您已经做过const sphynx = new Sphynx()

attemptAnswer()不返回任何内容,在Javascript中,如果不返回任何内容,则基本上返回undefined。因此,未定义响应是正常的。

在您的情况下,我将使用 for循环,而不是 forEach

attemptAnswer(guess) {
  for (let i = 0; i < this.riddles.length; i++) {
    if (guess === this.riddles[i].answer) {
      this.riddles.splice(index, 1);
      return "That wasn't that hard, I bet you don't get the next one.";
    }
  }
  return "Not found";
}

不建议在forEach中使用.splice()

使用forEach,将遍历数组中的所有项目,即使您已经找到答案。