gpt4 book ai didi

javascript - 当 start 未定义时,数组的 lastIndexOf 返回 -1

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:37:03 24 4
gpt4 key购买 nike

在javascript中,数组实例有两个方法,

[].indexOf(searchvalue [,start])

[].lastIndexOf(searchvalue [,start])

如果“开始”参数未定义,它会表现得很奇怪:

[1,2,3].lastIndexOf(2) // 1
[1,2,3].lastIndexOf(2,undefined) // -1
[1,2,3].indexOf(2,undefined) // 1

这发生在 chrome 和 firefox 中,那么 indexOf 和 lastIndexOf 以不同方式对待“未定义”的理论是什么

最佳答案

array.lastIndexOf(searchElement[, fromIndex])

fromIndex The index at which to start searching backwards. Defaults to the array's length, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, the whole array will be searched. If negative, it is taken as the offset from the end of the array. Note that even when the index is negative, the array is still searched from back to front. If the calculated index is less than 0, -1 is returned, i.e. the array will not be searched.

[1,2,3].lastIndexOf(2,undefined)[1,2,3].lastIndexOf(2, 0) 相同,因此只会搜索第一个元素。

[1,2,3].lastIndexOf(2, 0) 将返回 -1

[1,2,3].lastIndexOf(1, 0) 将返回 0

关于javascript - 当 start 未定义时,数组的 lastIndexOf 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11928951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com