【发布时间】:2013-12-30 07:37:05
【问题描述】:
我正在阅读 Nicholas Zakas 的“Professional JavaScript for Web Developers”(第三版),试图自学 JS。但是,我很难遵循第 118 页第 5 章的定位方法部分(如果您有这本书)。他解释说“indexOf() 方法从数组的前面(第 0 项)开始搜索并继续到后面,而 lastIndexOf() 从数组中的最后一项开始并继续到前面”。他还解释说“这些方法中的每一个都接受两个参数:要查找的项目和开始查找的可选索引”。然后他试图用例子来说明这一点。
如下所示,在警报语句的右侧,他列出了在给定参数的情况下每个语句的正确输出。我不明白这些输出是如何确定的。比如alert(numbers.indexOf(4));生产 3?昨晚我正在阅读这篇文章,并认为我太累了,无法理解,但是,我似乎仍然无法弄清楚这是如何实现的。我从本书的配套网站搜索勘误表部分,寻找可能的错字,但没有列出任何内容。我还在其他地方进行了搜索,但发现了主要处理字符串而不是数字的示例。谢谢你的帮助。这是我第一篇堆栈溢出的帖子,如果我在帖子中做错了什么,我深表歉意。
他的例子:
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.
任何帮助确定基于所需参数的输出,然后在给定附加可选参数的情况下如何从指定值计数,将不胜感激。再次感谢。
【问题讨论】:
-
嗯,JS 数组从 0 开始计数(即第一项是 index = 0)
-
“这是我第一篇堆栈溢出的帖子,如果我在帖子中做错了什么,我深表歉意。” - 你的帖子绝对没问题。好工作!欢迎来到 StackOverflow!
标签: javascript methods indexof