小编bon*_*igh的帖子

JavaScript,使用indexOf()和lastIndexOf()方法查找数组实例

我正在阅读尼古拉斯扎卡斯的"网络开发人员专业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 …
Run Code Online (Sandbox Code Playgroud)

javascript methods indexof

4
推荐指数
1
解决办法
374
查看次数

标签 统计

indexof ×1

javascript ×1

methods ×1