2

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

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。

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

4

3 回答 3

2

答案在您的分析中是正确的:

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

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

line.indexOf(line[i+1])

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

把它传给indexOf电话,你说的是,找到我undefinedline数组中的位置。 line包含“莎拉”、“迈克”和“鲍勃”。它不包含undefined.

我对这条线做了一个小改动array.push,它现在可以正常工作了:

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);
于 2016-09-04T03:56:06.797 回答
1

问题${line.indexOf(line[i+1])}在于,在最后一次迭代中,i2,它检查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);

于 2016-09-04T03:56:54.047 回答
0

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

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

应该是:

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

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

于 2016-09-04T03:53:35.193 回答