Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中是否有indexOf用于使用自定义比较函数搜索数组_Javascript_Underscore.js_Indexof - Fatal编程技术网

javascript中是否有indexOf用于使用自定义比较函数搜索数组

javascript中是否有indexOf用于使用自定义比较函数搜索数组,javascript,underscore.js,indexof,Javascript,Underscore.js,Indexof,我需要数组中与自定义比较函数匹配的第一个值的索引 非常好的函数有一个“find”函数,它返回函数返回true的第一个值,但我需要这个函数返回索引。是否有indexOf的版本可供使用,在那里我可以传递用于比较的函数 谢谢你的建议 您可以这样做: Array.prototype.myIndexOf = function(f) { for(var i=0; i<this.length; ++i) { if( f(this[i]) ) ret

我需要数组中与自定义比较函数匹配的第一个值的索引

非常好的函数有一个“find”函数,它返回函数返回true的第一个值,但我需要这个函数返回索引。是否有indexOf的版本可供使用,在那里我可以传递用于比较的函数


谢谢你的建议

您可以这样做:

Array.prototype.myIndexOf = function(f)
{
    for(var i=0; i<this.length; ++i)
    {
        if( f(this[i]) )
            return i;
    }
    return -1;
};
Array.prototype.myIndexOf=函数(f)
{

对于(var i=0;i使用下划线,我从他们的find实现中复制了一些东西,使用u2; any:

findIndex = function (obj, iterator, context) {
    var idx;
    _.any(obj, function (value, index, list) {
        if (iterator.call(context, value, index, list)) {
            idx = index;
            return true;
        }
    });
    return idx;
};

您认为如何?您有更好的解决方案吗?

下面是下划线方法-这将使用一个接受迭代器函数的函数来扩充核心下划线函数:

// save a reference to the core implementation
var indexOfValue = _.indexOf;

// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({

    // return the index of the first array element passing a test
    indexOf: function(array, test) {
        // delegate to standard indexOf if the test isn't a function
        if (!_.isFunction(test)) return indexOfValue(array, test);
        // otherwise, look for the index
        for (var x = 0; x < array.length; x++) {
            if (test(array[x])) return x;
        }
        // not found, return fail value
        return -1;
    }

});

_.indexOf([1,2,3], 3); // 2
_.indexOf([1,2,3], function(el) { return el > 2; } ); // 2
//保存对核心实现的引用
var indexOfValue=uxof.indexOf;
//使用.mixin可以进行包装调用和取消包装调用:
//_xOf(数组).indexOf(…)和xOf(数组…)
_.米辛({
//返回通过测试的第一个数组元素的索引
indexOf:函数(数组、测试){
//如果测试不是函数,则委托给标准indexOf
if(!.isFunction(test))返回indexOfValue(数组,test);
//否则,请查找索引
对于(var x=0;x2;});//2

javascript数组方法过滤器返回数组的子集,该子集从传递的函数返回true

var arr= [1, 2, 3, 4, 5, 6],
first= arr.filter(function(itm){
    return itm>3;
})[0];
alert(first);

if you must support IE before #9 you can 'shim' Array.prototype.filter-

Array.prototype.filter= Array.prototype.filter || function(fun, scope){
    var T= this, A= [], i= 0, itm, L= T.length;
    if(typeof fun== 'function'){
        while(i<L){
            if(i in T){
                itm= T[i];
                if(fun.call(scope, itm, i, T)) A[A.length]= itm;
            }
            ++i;
        }
    }
    return A;
}
var arr=[1,2,3,4,5,6],
first=arr.filter(功能(itm){
返回itm>3;
})[0];
警报(第一);
如果您必须在#9之前支持IE,则可以“shim”Array.prototype.filter-
Array.prototype.filter=Array.prototype.filter | |函数(fun,scope){
var T=this,A=[],i=0,itm,L=T.length;
if(typeof fun=='function'){

而(i这样的查找函数呢

(function () {
  if (!Array.prototype._find) {
    Array.prototype._find = function (value) {
      var i = -1, j = this.length;
      if (typeof(value)=="function") 
         for(; (++i < j) && !value(this[i]););
      else
         for(; (++i < j) && !(this[i] === value););

      return i!=j ? i : -1;
    }
  }
}());
(函数(){
如果(!Array.prototype.\u find){
Array.prototype.\u find=函数(值){
变量i=-1,j=this.length;
if(类型(值)=“功能”)
对于(;(++i
这是纳拉比诺维茨的咖啡脚本版本

#保存对核心实现的引用
indexOfValue=\ u0.indexOf
#使用.mixin可以进行包装调用和取消包装调用:
#_xOf(数组).indexOf(…)和xOf(数组…)
_.米辛({
#返回通过测试的第一个数组元素的索引
indexOf:(数组,测试)->
#如果测试不是函数,则委托给标准indexOf
如果(!.isFunction(测试))
返回indexOfValue(数组,测试)
#否则,请查找索引
对于项,数组中的i
返回i if(测试(项目))
#未找到,返回失败值
返回-1
})

正如其他人所指出的,您可以很容易地推出自己的产品,您可以根据自己的特定用例保持简洁:

// Find the index of the first element in array
// meeting specified condition.
//
var findIndex = function(arr, cond) {
  var i, x;
  for (i in arr) {
    x = arr[i];
    if (cond(x)) return parseInt(i);
  }
};

var moreThanTwo = function(x) { return x > 2 }
var i = findIndex([1, 2, 3, 4], moreThanTwo)
或者如果你是一名咖啡编剧:

findIndex = (arr, cond) ->
  for i, x of arr
    return parseInt(i) if cond(x)
ECMAScript 2015中针对
Array.prototype.findIndex()
有一个新版本。目前,除了Internet Explorer之外,它在所有主要浏览器中都有实现

这是polyfill,由以下人员提供:

//https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
if(!Array.prototype.findIndex){
Object.defineProperty(Array.prototype,'findIndex'{
值:函数(谓词){
//1.设O为?ToObject(该值)。
if(this==null){
抛出新的TypeError(“'this'为null或未定义”);
}
var o=对象(此);
//2.设len为?ToLength(?Get(O,“length”))。
var len=o.length>>>0;
//3.如果IsCallable(谓词)为false,则抛出TypeError异常。
if(类型谓词!=='function'){
抛出新类型错误('谓词必须是函数');
}
//4.如果提供了thisArg,则T为thisArg;否则T为未定义。
var thisArg=参数[1];
//5.设k为0。
var k=0;
//6.当k
我认为您的方法在这里通常是错误的。您不希望功能修改默认功能(重载
==
),您需要自己的功能(例如
myIndexOf
)。前者比后者更具破坏性和危险性。如果您的目标环境支持ES2015,lodash就可以做到这一点(或者您有一个transfile步骤,例如使用Babel),您可以使用本机的Array.prototype.findIndex()。感谢您的关注。我也相信还有第二次机会。;)请强调为什么
Array.prototype.indexOf(函数)
是一种错误的方法,我会给你那一票。谢谢这一票。我可以使用这一票,而不将它添加到Array.prototype。最好不要添加到Array.prototype,除非你为一个标准中但不受特定实现支持的函数提供一个垫片。我不知道
是什么意思ns.我猜你在使用一些框架?如果是这样,请友好地告诉我们你的秘密;)。你不应该对
any
使用额外的函数,这会减慢方法的速度。只需使用一个简单的for循环谢谢,构建新的子集数组可能会降低性能-怎么办
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
if (!Array.prototype.findIndex) {
  Object.defineProperty(Array.prototype, 'findIndex', {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return k.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return k;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return -1.
      return -1;
    },
    configurable: true,
    writable: true
  });
}