我正在阅读Nicholas Zakas的《Web开发者专业JavaScript》(第三版),希望能自学JS。然而,在第5章的“位置方法”一节,我在第118页上遇到了困难(如果你有这本书的话)。他解释说,“indexOf()方法从数组的前端(项0)开始搜索,并继续到后端,而lastIndexOf()则从数组的最后一项开始,继续到前面”。此外,他解释道:“每个方法都接受两个参数:要查找的项和一个可选的索引,从哪里开始查找。” 然后,他试图用例子来说明这个问题。
如下所示,在警告语句的右侧,他列出了在提供的参数情况下每个语句的正确输出。我不明白这些输出是如何确定的。例如,警报(数字.indexOf(4)); 如何产生3?昨晚我看到这个后觉得可能是太累了,不过今天我仍然无法弄清楚这是如何实现的。我在书的附属网站的勘误部分中搜索可能的印刷错误,但没有列出任何内容。我还在其他地方搜索,但发现大多数例子都涉及到字符串而不是数字。感谢任何帮助。这是我在Stack Overflow上的第一篇文章,如果我的文章有任何错误请见谅。
如下所示,在警告语句的右侧,他列出了在提供的参数情况下每个语句的正确输出。我不明白这些输出是如何确定的。例如,警报(数字.indexOf(4)); 如何产生3?昨晚我看到这个后觉得可能是太累了,不过今天我仍然无法弄清楚这是如何实现的。我在书的附属网站的勘误部分中搜索可能的印刷错误,但没有列出任何内容。我还在其他地方搜索,但发现大多数例子都涉及到字符串而不是数字。感谢任何帮助。这是我在Stack Overflow上的第一篇文章,如果我的文章有任何错误请见谅。
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4)); //3
alert(numbers.lastIndexOf(4)); //5
alert(numbers.indexOf(4, 4)); //5
alert(numbers.lastIndexOf(4, 4)); //3
我最初的想法是:
alert(numbers.indexOf(4));
//the item in the array with the fourth index, or 5
alert(numbers.lastIndexOf(4));
//5 (this was only one that seemed to make sense to me) by counting back from the last value
alert(numbers.indexOf(4, 4));
//start looking at index 4, or 5, and then count right four places to end up at 1 (last item in array).
alert(numbers.lastIndexOf(4, 4));
//1, counting back to the left from the value with index 4, or 5, to reach the first value in the array.
非常感谢您的支持,在确定所需参数的输出结果以及如何根据给定的其他可选参数计数时,任何帮助都将不胜感激。再次感谢。