Last active
December 20, 2015 01:49
-
-
Save coolicer/6051658 to your computer and use it in GitHub Desktop.
_.each
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var each = _.each = _.forEach = function(obj, iterator, context) { | |
| if (obj == null) return; | |
| if (nativeForEach && obj.forEach === nativeForEach) { | |
| //如果是数组,使用数组原生的forEach | |
| obj.forEach(iterator, context); | |
| } else if (obj.length === +obj.length) { | |
| //如果是数组,且没有原生方法 | |
| for (var i = 0, l = obj.length; i < l; i++) { | |
| if (iterator.call(context, obj[i], i, obj) === breaker) return; | |
| } | |
| } else { | |
| //如果是对象 | |
| for (var key in obj) { | |
| if (_.has(obj, key)) { // _.has 判断 属性/方法 是否来自该对象,不会检查到原型链上 | |
| if (iterator.call(context, obj[key], key, obj) === breaker) return; | |
| } | |
| } | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment