#javascript #arrays #function
Вопрос:
Я хотел бы получить некоторую помощь, пожалуйста, вы видите, что я должен был определить в упражнении 6, включал ли массив имя «уолдо» и прошла ли моя функция тесты, она прошла, и консоль зарегистрировала значение true для обоих тестов. Теперь в упражнении 7 он хочет, чтобы я сделал это снова, определил, содержит ли массив «waldo», и если да, то моя функция должна пройти этот тест. Мои проблемы, если я перепробовал так много разных сценариев, и я продолжаю получать, чтобы консоль регистрировала ложь для обоих тестов или выдавала мне сообщение об ошибке «arrayOfNames», не определено. Я пытаюсь воспользоваться подсказкой и просто вызвать свою функцию containsWaldo, но безуспешно. Любое представление о том, что я здесь делаю не так, я скопировал в вопросы для обоих упражнений, чтобы сделать это, надеюсь, более ясным. Заранее спасибо.
----------------------------
console.log("Exercise Six");
// - Given the arrayOfNames, determine if the array contains the name "waldo".
// - The name waldo will be all lower-case.
// - If the array contains "waldo", return true. If it does not, return false.
// - Hint: You don't have to write another loop, or copy-paste your previous function.
// Just call your previous function, "contains," with the array and the name "waldo" and return the result.
//
// Write your code here 👇
function containsWaldo(arrayOfNames) {
return contains(arrayOfNames, "waldo");
}
// -------TESTS---------------------------------------------------------------
// Run these commands to make sure you did it right. They should all be true.
console.log("-----Tests for Exercise Six-----");
console.log("* Returns true when waldo is in an array");
console.log(containsWaldo(["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"]) === true);
console.log("* Returns false when waldo is not in the array");
console.log(containsWaldo(["bob", "nancy", "john", "shawnie", "shaquon", "julie"]) === false);
// ----------------------------------------------------------------------------------------------
console.log("Exercise Seven");
// - Given the arrayOfNames, if the array contains waldo, then return "I found waldo!"
// If the array does not contain waldo, then return "I couldn't find waldo..."
// - Hint: Don't actually search for waldo! Just call your other function, "containsWaldo".
//
// Write your code here 👇
function searchForWaldo(arrayOfNames) {
return containsWaldo(arrayOfNames);
}
// my code here, will log false for both test cases
// -------TESTS---------------------------------------------------------------
// Run these commands to make sure you did it right. They should all be true.
console.log("-----Tests for Exercise Seven-----");
console.log("* Returns 'I found waldo!' when waldo is in an array");
console.log(searchForWaldo(["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"]) === "I found waldo!");
console.log("* Returns 'I couldn't find waldo...' when waldo is not in the array");
console.log(searchForWaldo(["bob", "nancy", "john", "shawnie", "shaquon", "julie"]) === "I couldn't find waldo...");
Ответ №1:
Они возвращают значение false, потому что вы сравниваете логическое значение со строковым значением.
console.log(searchForWaldo(["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"]) === "I found waldo!");
console.log(searchForWaldo(["bob", "nancy", "john", "shawnie", "shaquon", "julie"]) === "I couldn't find waldo...");
Сравнение, которое вы пытаетесь сделать, это:
console.log(searchForWaldo(["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"]) === true);
console.log(searchForWaldo(["bob", "nancy", "john", "shawnie", "shaquon", "julie"]) === true);
Тем не менее, вам нужно записать строку в консоль, а не значение логического значения.
Комментарии:
1. Спасибо, у меня были трудные времена с этим.
Ответ №2:
Что для этого нужно сделать, написано прямо здесь:
// - Given the arrayOfNames, if the array contains waldo, then return "I found waldo!"
// If the array does not contain waldo, then return "I couldn't find waldo..."
function searchForWaldo(arrayOfNames) {
return containsWaldo(arrayOfNames) ? 'I found waldo!' ? 'I couldn't find waldo...'
}
Более того, в этом коде нет ни одного вложенного массива.
Комментарии:
1. Спасибо вам за помощь.
Ответ №3:
// Exercise Six
const contains = (arr, needle) => arr.includes(needle);
// Exercise Seven
const contains = (arr, needle) => arr.includes(needle) ? "I found waldo!" : "I couldn't find waldo...";
Комментарии:
1. Спасибо, я ценю ваше объяснение.