【问题标题】:javascript function to determine if an array contains a value [duplicate]用于确定数组是否包含值的javascript函数[重复]
【发布时间】:2021-04-10 01:51:00
【问题描述】:

第一次测试我得到“假”,第二次测试我得到“真”。我想创建一个将评估这些值的函数。我以为我在函数中正确执行了我的代码,但我没有得到我想得到的东西。我不明白我在这里做错了什么。任何帮助将不胜感激。谢谢。

// - 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 ????

function contains(arrayOfNames, name) {
  for (index = 0; index < arrayOfNames.length; index++) {
    if (arrayOfNames[index] === name) {
      return true;
    } else {
      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);

【问题讨论】:

标签: javascript arrays function


【解决方案1】:

仅当数组不包含 name 时才返回 false

您要做的是,如果找到match,它将返回true,但一旦找不到匹配项arrayOfNames[index] === name),它将返回false

在你的第一个例子中:假设i=0,第一个元素是bob。所以arrayOfNames[index]bob 而你要搜索的namenancy。所以当它匹配它们时它不相等,所以它会返回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
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-03
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2018-04-23
    • 2019-10-03
    相关资源
    最近更新 更多