【问题标题】:Understanding how the JS engine is looping through to get the index of an array element了解 JS 引擎如何循环获取数组元素的索引
【发布时间】:2016-09-04 03:45:49
【问题描述】:

我写了一个函数来输出排队等候的人的姓名和现实生活中的索引。

var line = ["Sarah", "Mike", "Bob"];

function currentLine(line) {
  if (line.length === 0) {
    document.write(`The line is currently empty.`);
  } else {

    var array = [];
    for (var i = 0; i < line.length; i++) {
      array.push(` ${line.indexOf(line[i+1])}. ${line[i]}`);
    }
    document.write(`The line is currently:` + array);
  }
}

currentLine(line);

当我运行函数时,输出是:

The line is currently: 1. Sarah, 2. Mike, -1. Bob

JavaScript 引擎如何解释循环?鲍勃-1怎么样?上次我检查了 2 + 1 = 3。

我想自己解决这个问题,但我试图了解这个看似简单的循环中发生了什么。

【问题讨论】:

    标签: javascript loops iterator javascript-engine


    【解决方案1】:

    答案在您的分析中:

    鲍勃-1怎么样?上次我检查 2 + 1 = 3

    在循环的第三次迭代中,i = 2。此行以 i = 2 执行:

    line.indexOf(line[i+1])
    

    那么这说明了什么?它说给我位置(i + 1) 的元素,即位置3,或forth 元素。没有第四个元素,所以line[i+1]undefined

    将其传递给indexOf 调用,您的意思是,在line 数组中找到undefined 的位置。 line 包含“Sarah”、“Mike”和“Bob”。它不包含undefined

    我对@9​​87654330@ 行做了一个小改动,现在它可以正常工作了:

    var line = ["Sarah", "Mike", "Bob"];
    
    function currentLine(line) {
      if (line.length === 0) {
        document.write(`The line is currently empty.`);
      } else {
    
        var array = [];
        for (var i = 0; i < line.length; i++) {
          array.push(` ${i+1}. ${line[i]}`);
        }
        document.write(`The line is currently:` + array);
      }
    }
    
    currentLine(line);
    

    【讨论】:

    • 非常感谢@Brandon。计算思维对于新手来说是一次旅行。解释得这么好是有道理的。非常感谢。
    【解决方案2】:

    ${line.indexOf(line[i+1])} 的问题在于,在最后一次迭代中,i 为 2,它会检查 line[3]。那不存在,所以它吐出一个-1,因为这是indexOf的返回值,如果某些东西不存在的话。就这样吧:

    array.push(` ${i+1}. ${line[i]}`);
    

    这只是打印i + 1,而不是寻找索引。

    var line = ["Sarah", "Mike", "Bob"];
    
    function currentLine(line) {
      if (line.length === 0) {
        document.write(`The line is currently empty.`);
      } else {
        var array = [];
        for (var i = 0; i < line.length; i++) {
          console.log(line.indexOf(line[i+1])); //On last iteration, it's -1 because it's not found in the array!
          array.push(` ${i+1}. ${line[i]}`);
        }
        document.write(`The line is currently:` + array);
      }
    }
    
    currentLine(line);

    【讨论】:

      【解决方案3】:

      我修复了循环。我使索引过于复杂:

      ${line.indexOf(line[i+1])}

      应该是:

      ${[i+1]} - 这是合法的语法吗?

      另外,如果有人能阐明我的错误代码在做什么以及 JS 是如何迭代的,我将不胜感激。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-12
        • 2021-08-17
        • 1970-01-01
        相关资源
        最近更新 更多