【问题标题】:JavaScript string count loop misunderstandingJavaScript 字符串计数循环误解
【发布时间】:2019-02-05 18:13:41
【问题描述】:

我在完成一项基本任务时遇到了问题。我需要编写一个 JavaScript 程序,它包含一个至少包含五个字符串的数组,循环遍历该数组,并为每个项目调用一个函数;这个函数应该检查字符串有多长:

  • 如果字符串少于四个字符,则打印短语“Less Than Four”
  • 如果等于四个字符,则打印“正好四个”
  • 如果超过四个,打印“More Than Four”

我尝试了很多东西,但感觉我找错了地方。我知道这是基本的,但我似乎无法理解这个......

我现在的代码:

var colors = ["teal", "violet", "silver", "green", "red", "purple"];
var count;

for (count = 0; count < colors.length; count++) {
  console.log(colors[count]);
}

if (colors > 4) {
  console.log("greater than 4");
}

if (colors < 4) {
  console.log("less than 4");
}

if (colors = 4) {
  console.log("is equal to 4");
}

【问题讨论】:

  • 您应该在for-loop 中检查每个字符串的length 属性。例如console.log(colors[count].length).
  • 您还需要将您的ifs 移动到for 块内并使用正确的比较;在最后一个 if 中,您是 assigning 而不是 comparing
  • and = 是赋值,== 或 === 是比较 colors[count].length === 4) 在循环内移动 ifs

标签: javascript arrays string loops variables


【解决方案1】:

数组有内置的循环方法,允许在每次循环迭代时执行回调函数。在您的场景中,由于您只需要检查字符串,因此.forEach() 方法可能是最合适的。

在函数中,您只需要一个简单的if/then/else 语句来确定要打印哪条消息。

var colors = ["teal", "violet", "silver", "green", "red", "purple"];

colors.forEach(function(color){
  if(color.length < 4){
    console.log(color + " has less than 4 characters.");
  } else if (color.length === 4) {
    console.log(color + " has 4 characters.");  
  } else {
    console.log(color + " has more than 4 characters.");  
  } 
});

【讨论】:

    【解决方案2】:

    较新版本的 JavaScript 支持 for..of 语法

    const colors =
      [ "teal", "violet", "silver", "green", "red", "purple" ]
      
    for (const c of colors)
    { if (c.length > 4)
        console.log(c, "greater than 4")
      else if (c.length < 4)
        console.log(c, "less than 4")
      else
        console.log(c, "equal to 4")
    }
    
    // teal equal to 4
    // violet greater than 4
    // silver greater than 4
    // green greater than 4
    // red less than 4
    // purple greater than 4

    您应该使用函数将循环的关注点和长度检查分开 -

    const colors =
      [ "teal", "violet", "silver", "green", "red", "purple" ]
      
    const checkLength = str =>
    { if (str.length > 4)
        return "greater than 4"
      else if (str.length < 4)
        return "less than 4"
      else
        return "equal to 4"
    }
    
    for (const c of colors)
      console.log(c, checkLength(c))
    
    // teal equal to 4
    // violet greater than 4
    // silver greater than 4
    // green greater than 4
    // red less than 4
    // purple greater than 4

    JavaScript 是 multi-paradigm language,因此它支持以多种样式编写相同的程序 -

    const colors =
      [ "teal", "violet", "silver", "green", "red", "purple" ]
    
    const checkLength = str =>
    { if (str.length > 4)
        console.log(`${str} is greater than 4`)
      else if (str.length < 4)
        console.log(`${str} is less than 4`)
      else
        console.log(`${str} is equal to 4`)
    }
    
    colors.forEach(checkLength)
    
    // teal equal to 4
    // violet greater than 4
    // silver greater than 4
    // green greater than 4
    // red less than 4
    // purple greater than 4

    JavaScript 对表达式的支持也非常好,不需要像 ifelseswitchforfordo 甚至 return 这样的命令式关键字 -

    const colors =
      [ "teal", "violet", "silver", "green", "red", "purple" ]
    
    const checkLength = x =>
      x.length > 4                   // if ...
        ? `${x} is greater than 4`
    : x.length < 4                   // else if ...
        ? `${x} is less than 4`
    : `${x} is equal to 4`           // else
    
    console.log(colors.map(checkLength))
    
    // [ "teal is equal to 4"
    // , "violet is greater than 4"
    // , "silver is greater than 4"
    // , "green is greater than 4"
    // , "red is less than 4"
    // , "purple is greater than 4"
    // ]

    【讨论】:

    • 请让非常nooby noob首先学习纯JS并给他们良好的实践,例如括号内的陈述
    • 哇,太棒了
    • @mplungjan 我正在非常仔细地阅读您的评论,但我不明白。 “先学纯JS”是什么意思? 之后会有好的做法吗?为什么不先学习好的做法呢?什么是“括号内的陈述”
    • @mplungjan 我应该在学习 PHP 7 之前学习 PHP 5 吗?我应该在学习 Python 3 之前学习 Python 2 吗? "ES6" 正如你所说,在许多环境中得到广泛支持。为什么你认为学习者必须处理 IE?这和巴别塔有什么关系?你确定学习者正在浏览器中运行它吗?你的担忧告诉我,也许是 不知道如何“让非常nooby noob 学习普通的JS...”
    • @mplungjan 老了并不会让你的建议更明智。您无需编写 for 循环即可成为编程大师,但课堂课程围绕 Basic、C 和 C++ 构建,因此命令式风格主导着学习者的思维定势。在告诉计算机该做什么 15 年后,one book 向我展示了一切都可能不同。 “你必须从我开始的地方开始”的心态被打破了。
    【解决方案3】:

    在每个元素上调用一个函数并检查 if-else 块内的长度

    var colors = ["teal", "violet", "silver", "green", "red", "purple"];
    var count;
    
    for (count = 0; count < colors.length; count++) {
      console.log(colors[count]);
      stringLength(colors[count]);
    }
    
    function stringLength(string) {
      if (string.length > 4) {
        console.log("greater than 4");
      } else if (string.length < 4) {
        console.log("less than 4");
      } else {
        console.log("is equal to 4");
      }
    }

    【讨论】:

      【解决方案4】:

      您需要将 if 语句放在 for 循环的花括号内,因此对于每种颜色,它将遍历所有 if 条件并在匹配时打印。

      一种更惯用的方法是在 forEach 函数的主体中实现逻辑,该函数是 Array object's prototype 的一部分

      var colors = ["teal", "violet", "silver", "green", "red", "purple"];
      
      colors.forEach(function(currentColorToCheck) { //currentColorToCheck is a temporary variable that the forEach function gives you (1 for every item of colors Array)
        if (currentColorToCheck.length > 4) { // we use the .length function (part of String prototype and Array prototype) to get the length of the string
          console.log("greater than 4");
        }
      
        if (currentColorToCheck.length < 4) {
          console.log("less than 4");
        }
      
        if (currentColorToCheck.length === 4) { // here for an equality comparison, use === instead of =
          console.log("is equal to 4");
        }
      })
      

      forEach 是一种更方便的方式来表达“迭代数组的值”。您可以查看文档以获取更多指导。

      附带说明一下,每种 JavaScript 类型(对象、数组、字符串、数字、日期、数学等)都有大量原型(内置)函数,您可能想在业余时间学习这些函数。 Mozilla Developer Network 有很多资源。

      【讨论】:

      • 为什么不使用===
      • 其实是推荐的,现在更新代码。
      • 使用单独的if 语句,无论前面的结果如何,它们都将进行测试。应该是if/else if/else
      • @ScottMarcus 当然,我尝试尽可能忠实于原始代码,同时仍提供其他信息。
      猜你喜欢
      • 2013-11-28
      • 1970-01-01
      • 2020-07-06
      • 2016-02-08
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      相关资源
      最近更新 更多