Ped*_* T. 26 javascript indexof underscore.js
我需要数组中第一个值的索引,它与自定义比较函数匹配.
非常好的underscorej有一个"find"函数,它返回一个函数返回true的第一个值,但我需要这个函数来返回索引.是否有某个版本的indexOf可用于哪里,我可以传递一个用于比较的函数?
谢谢你的任何建议!
nra*_*itz 26
这是Underscore的方法 - 它使用一个接受迭代器函数的核心Underscore函数来增强它:
// 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
Run Code Online (Sandbox Code Playgroud)
Hus*_*sky 10
ECMAScript 2015中有一个标准功能Array.prototype.findIndex().目前,除了Internet Explorer之外,它还在所有主流浏览器中实现.
这是一个polyfill,由Mozilla开发者网络提供:
// 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
});
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
Array.prototype.myIndexOf = function(f)
{
for(var i=0; i<this.length; ++i)
{
if( f(this[i]) )
return i;
}
return -1;
};
Run Code Online (Sandbox Code Playgroud)
关于Christian的评论:如果你使用具有不同相同签名和不同功能的自定义JavaScript方法覆盖标准JavaScript方法,则可能会发生不好的事情.如果您正在使用可能依赖于原始数据的第三方库,例如Array.proto.indexOf,则尤其如此.所以,是的,你可能想把它称之为别的东西.
| 归档时间: |
|
| 查看次数: |
26557 次 |
| 最近记录: |