簡體   English   中英

如何編寫一個函數來通過 2 個測試

[英]How to write a function to pass 2 tests

我正在學習和練習使用 javascript 編寫測試:

這是測試用例find.test.js

var findTheNeedle = require("./find-needle");

test("Find the needle", function () {
  var words = ["house", "train", "slide", "needle", "book"];
  var expected = 3;

  var output = findTheNeedle(words, "needle");

  expect(output).toEqual(expected);
});

test("Find the plant", function () {
  var words = ["plant", "shelf", "arrow", "bird"];
  var expected = 0;

  var output = findTheNeedle(words, "plant");

  expect(output).toEqual(expected);
});

這是我的以下函數find.js

function findNeedle(words) {
  for (var i = 0; i < words.length; i++) {
    if (words[i] === "needle") {
      var needle = i;
    }
  }

  return needle;
}
module.exports = findNeedle;

你應該做這個:

var findTheNeedle = require("./find-needle");

test("Find the object", function () {
  var words = ["house", "train", "slide", "needle", "book"];
  var expected = 3;

  var output = findTheNeedle(words, "needle");

  expect(output).toEqual(expected);

  var words = ["plant", "shelf", "arrow", "bird"];
  var expected = 0;

  var output = findTheNeedle(words, "plant");

  expect(output).toEqual(expected);
});

我認為您需要重新制作該功能,如下所示:

function findInArray( arr, word ) {
  let index = -1
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === word) {
       index = i;
    }
  }

  return index;
}
module.exports = findInArray;

如果任何“期望”失敗,則所有測試都將失敗

看來您的函數將返回單詞列表中“單詞”的索引。 這意味着,您的函數必須接收 2 個變量作為參數:“word”和“words”。

我認為當前的函數名(和文件名) - findNeedle不“正確”,所以我建議更改它。 findWordIndex怎么樣?

函數邏輯很簡單,你可以使用Array.indexOf工具來做,或者按照你的方式來做。

module.exports = (words, word) => words.indexOf(word);

或者

module.exports = (words, word) => {
  for (let i = 0; i < words.length; i++) {
    if (words[i] === word) {
      return i; // stop right after you found it
    }
  }
  return -1;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM