YUI原码
YUI someYArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) {
return Native.some.call(array, fn, thisObj);
} : function (array, fn, thisObj) {
for (var i = 0, len = array.length; i < len; ++i) {
if (i in array && fn.call(thisObj, array[i], i, array)) {
return true;
}
}
return false;
};
qwrap原码
qwrap somesome: function(arr, callback, pThis) {
for (var i = 0, len = arr.length; i < len; i++) {
if (i in arr && callback.call(pThis, arr[i], i, arr)) {
return true;
}
}
return false;
}
tangram 1.x原码 2.0版本了已删除
tangram somebaidu.array.some = function(source, iterator, thisObject) {
var i = 0,
len = source.length;
for (; i < len; i++) {
if (i in source && iterator.call(thisObject || source, source[i], i)) {
return true;
}
}
return false;
};
underscore原码
underscore somevar any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
}
思路: 都是用for来循环,为每一个元素调用函数,如果符合条件就返回true,并跳出函数
比较:
YUI,qwrap,tangram三个的一样的处理方法,区别之处在于YUI可以引用原生的some方法,会抛出类型错误
underscore本质是其它三种是一样的,只不过借用了each与 || 的特性来调用函数,他还考虑到了null没用length属性,不会抛出错误