YUI原码
YUI indexOfYArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) {
return Native.indexOf.call(array, value, from);
} : function (array, value, from) {
// http://es5.github.com/#x15.4.4.14
var len = array.length; from = +from || 0;
from = (from > 0 || -1) * Math.floor(Math.abs(from));//取整 if (from < 0) {
from += len; if (from < 0) {
from = 0;
}
} for (; from < len; ++from) {
if (from in array && array[from] === value) {
return from;
}
} return -1;
};
tangram – indexOf 原码
tangram indexOfvar T,baidu=T= function(){
///import baidu.array; baidu.array.extend({
indexOf : function (match, fromIndex) {
baidu.check(".+(,number)?","baidu.array.indexOf");
var len = this.length; // 小于 0
(fromIndex = fromIndex | 0) < 0 && (fromIndex = Math.max(0, len + fromIndex)); for ( ; fromIndex < len; fromIndex++) {
if(fromIndex in this && this[fromIndex] === match) {
return fromIndex;
}
} return -1;
}
});
return baidu;
}();
underscore原码
underscore indexOf_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
qwrap原码
qwrap indexOfindexOf: function(arr, obj, fromIdx) {
var len = arr.length;
fromIdx |= 0; //取整
if (fromIdx < 0) {
fromIdx += len;
}
if (fromIdx < 0) {
fromIdx = 0;
}
for (; fromIdx < len; fromIdx++) {
if (fromIdx in arr && arr[fromIdx] === obj) {
return fromIdx;
}
}
return -1;
}
比较
1.不同在于几个对于起始位置的处理
a. YUI的处理看来来复杂,但是它是根据ES5中的标准步骤进行的
b. underscore是唯一一个没用对起始值取整的且不支持负值,但它提供了对大数组提供二进制搜索的功能
c. underscore针对null做了特殊处理,防止抛出错误,影响后续进行
d. 比较之下,对于起始位置的处理,倾向于tangram的做法,简洁明了,充分利用了各种运算符的特性
(fromIndex = fromIndex | 0 ) < 0 && (fromIndex = Math.max(0, len + fromIndex))