松散类型的indexOf()? [英] A loosely-typed indexOf()?

查看:237
本文介绍了松散类型的indexOf()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有数组:

[1, 2, 3, 4]

现在让我们假设我想知道, == S(未 === 多个)给定的值,例如3。对于这种情况下,我希望回到2,但Array.indexOf返回-1。

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.

推荐答案

嗯,有天真的执行...

Well, there's the naive implementation ...

function looseIndex(needle, haystack) {
  for (var i = 0, len = haystack.length; i < len; i++) {
    if (haystack[i] == needle) return i;
  }
  return -1;
}

例如

> [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`

(这种方法的一个好处是,它与像节点列表参数 S中的可能不是对象支持全阵列API)。

(One bonus of this approach is that it works with objects like NodeLists and arguments that may not support the full Array API.)

如果您的数组排序,你可以做的更好的性能二进制搜索。请参见 Underscore.js'sortedIndex code 一个例子

If your array is sorted, you can do a binary search for better performance. See Underscore.js' sortedIndex code for an example

这篇关于松散类型的indexOf()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆