<!DOCTYPE HTML> <html> <body> </body> <script type="text/javascript"> (function(root) { var push = Array.prototype.push; var _ = function(obj) { if (obj instanceof _) { return obj; } if (!(this instanceof _)) { return new _(obj); } this._wrapped = obj; } var cb = function(iteratee, context, count) { if (iteratee == null) { return _.identity; } if (_.isFunction(iteratee)) { return optimizeCb(iteratee, context, count); } } //optimizeCb優化迭代器 var optimizeCb = function(func, context, count) { if (context == void 0) { return func; } switch (count == null ? 3 : count) { case 1: return function(value) { return func.call(context, value); }; case 3: return function(value, index, obj) { return func.call(context, value, index, obj); }; case 4: return function(memo, value, index, obj) { return func.call(context, memo, value, index, obj); }; } } _.isArray = function(array) { return toString.call(array) === "[object Array]"; } _.each = function(target, callback) { var key, i = 0; if (_.isArray(target)) { var length = target.length; for (; i < length; i++) { callback.call(target, target[i], i); } } else { for (key in target) { callback.call(target, key, target[key]); } } } _.each(["Function", "String", "Object", "Number", "Boolean", "Arguments"], function(name) { _["is" + name] = function(obj) { return toString.call(obj) === "[object " + name + "]"; } }); //predicate 真值檢測(重點: 返回值) _.filter = function(obj, predicate, context) { var results = []; predicate = cb(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; root._ = _; })(this); /*思路:定義一個underscore的filter函數,由於只有NaN是不等於自身的,因此真值檢測中設置返回等於自身的元素 */ var arr = [NaN ,1,21,32,NaN,41,5]; var bb = _.filter(arr,function(num) { return num === num; }); console.log(bb);//[1, 21, 32, 41, 5] </script> </html>