javascript函数来确定数组是否包含值
我在第一次测试中得到'false',在第二次测试中得到'true'。我假设创建一个函数,该函数将计算这些值。我认为我在函数中正确地执行了代码,但是我没有得到我应该得到的。我不明白我在这里会做错什么。任何帮助都将不胜感激。谢谢javascript函数来确定数组是否包含值,javascript,arrays,function,Javascript,Arrays,Function,我在第一次测试中得到'false',在第二次测试中得到'true'。我假设创建一个函数,该函数将计算这些值。我认为我在函数中正确地执行了代码,但是我没有得到我应该得到的。我不明白我在这里会做错什么。任何帮助都将不胜感激。谢谢 // - Given the arrayOfNames, determine if the array contains the given name. // - If the array contains the name, return true. If it doe
// - Given the arrayOfNames, determine if the array contains the given name.
// - If the array contains the name, return true. If it does not, return false.
// - Hint: Use a loop to "iterate" through the array, checking if each name matches the name parameter.
//
// Write your code here Return false
only if the array doesn't contain the name
.
What you're trying to do is it will return true
if the match
found but it will return false
as soon as the match not found arrayOfNames[index] === name)
.
In you first example: Let say i=0
and the first element is bob
. So the arrayOfNames[index]
is bob
and the name
you want to search is nancy
. So when it matches them it is not equal so it will return false
.
function contains(arrayOfNames, name) {
for (let index = 0; index < arrayOfNames.length; index++) {
if (arrayOfNames[index] === name) {
return true;
}
}
return false;
}
// -------TESTS---------------------------------------------------------------
// Run these commands to make sure you did it right. They should all be true.
console.log("-----Tests for Exercise Five-----");
console.log("* Returns true when the array contains the name.");
console.log(
contains(
["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"],
"nancy"
) === true
);
console.log("* Returns false when the name is not in the array");
console.log(
contains(
["bob", "nancy", "john", "shawnie", "waldo", "shaquon", "julie"],
"fred"
) === false
);
/-给定arrayOfNames,确定数组是否包含给定名称。
//-如果数组包含名称,则返回true。如果没有,则返回false。
//-提示:使用循环“迭代”数组,检查每个名称是否与name参数匹配。
//
//仅当数组不包含名称时,才在此处编写代码返回false
您试图做的是,如果找到了匹配项,它将返回true
,但一旦未找到匹配项,它将返回false
在第一个示例中:假设i=0
,第一个元素是bob
。因此,arrayOfNames[index]
是bob
,您要搜索的name
是nancy
。因此,当它与它们匹配时,它是不相等的,因此它将返回false
函数包含(arrayOfNames,名称){
for(让index=0;index请参阅: