bon*_*igh 4 javascript methods indexof
我正在阅读尼古拉斯扎卡斯的"网络开发人员专业JavaScript"(第三版),试图自学JS.但是,我很难按照第118页第5章的"位置方法"部分进行操作(如果您有本书).他解释说"indexOf()方法从数组的前面开始搜索(项目0)并继续向后搜索,而lastIndexOf()从数组的最后一项开始并继续到前面".他还解释说"这些方法中的每一个都接受两个参数:要查找的项目和从中开始查找的可选索引".然后,他试图用例子说明这一点.
如下所示,在alert语句的右侧,他列出了给定所提供参数的每个语句的正确输出.我不明白这些产出是如何确定的.例如,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
Run Code Online (Sandbox Code Playgroud)
我认为结果的方式是:
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.
Run Code Online (Sandbox Code Playgroud)
任何帮助确定基于所需参数的输出,然后如何在给定附加可选参数的情况下从指定值计数将非常感激.再次感谢.
在大多数编程语言中,默认索引从0开始.因此,您有一个理解问题.双重考虑你的例子,索引从0开始.
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4)); //3, because 4 is at 3rd index
alert(numbers.lastIndexOf(4)); //5, because last 4 is at 5th index
alert(numbers.indexOf(4, 4)); //5, because searching will start from 4th index
alert(numbers.lastIndexOf(4, 4)); //3, because searching will start from last 3rd element.
Run Code Online (Sandbox Code Playgroud)