Let's suppose I have the array:
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
Now let's suppose I want to know the first index of a value that ==s (not ===s) a given value, like "3". For this case I would want to return 2, but Array.indexOf returns -1.
:(
Update 2021-04-13: ES6 introduced findIndex() and arrow functions, so you can now do...
> [1,2,3,4].findIndex(v => v == '3')
2
Run Code Online (Sandbox Code Playgroud)
[Original answer]
嗯,有一个天真的实现......
function looseIndex(needle, haystack) {
for (var i = 0, len = haystack.length; i < len; i++) {
if (haystack[i] == needle) return i;
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
例如
> [0,1,2].indexOf('1')
-1 // Native implementation doesn't match
> looseIndex('1', [0, 1, 2])
1 // Our implementation detects `'1' == 1`
> looseIndex('1', [0, true, 2])
1 // ... and also that `true == 1`
Run Code Online (Sandbox Code Playgroud)
(这种方法的一个好处是它适用于可能不支持完整 Array API 的NodeLists 和arguments等对象。)
如果您的数组已排序,您可以进行二分搜索以获得更好的性能。有关示例,请参阅Underscore.js 的 sortedIndex 代码
indexOf does strict equals, so do a conversion on either of the sides, You can try this way:
Either:
arr.map(String).indexOf("3");
Run Code Online (Sandbox Code Playgroud)
or
var str = "3";
arr.indexOf(+str);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |