Javascript Underline.js库中的每个实现
关于“each”函数实现的问题,我在underline.js源代码(下面的源代码)中找到 首先,有人能解释一下“else if(obj.length===+obj.length)”这一行在检查什么吗 第二,有人能解释为什么使用hasOwnProperty.call(obj,key)而不是obj.hasOwnProperty吗?是不是因为传入的obj可能没有实现hasOwnProperty(我认为每个javascript对象都实现了) 任何见解都值得赞赏。谢谢Javascript Underline.js库中的每个实现,javascript,Javascript,关于“each”函数实现的问题,我在underline.js源代码(下面的源代码)中找到 首先,有人能解释一下“else if(obj.length===+obj.length)”这一行在检查什么吗 第二,有人能解释为什么使用hasOwnProperty.call(obj,key)而不是obj.hasOwnProperty吗?是不是因为传入的obj可能没有实现hasOwnProperty(我认为每个javascript对象都实现了) 任何见解都值得赞赏。谢谢 // The cornersto
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
//基石,一个'each'实现,又称'forEach'。
//使用内置的“forEach”、数组和原始对象处理对象。
//委派到**ECMAScript 5**的本机“forEach”(如果可用)。
var each=u0.each=0.forEach=函数(对象、迭代器、上下文){
if(obj==null)返回;
if(nativeForEach&&obj.forEach===nativeForEach){
forEach(迭代器,上下文);
}否则如果(对象长度===+对象长度){
对于(变量i=0,l=obj.length;i
这是:
+obj.length
…将对length
的值进行色调转换
看起来好像他们正在通过进行toNumber转换来确保length
引用了一个数字,并验证转换后的数字仍然是相同的
如果是这样,他们假设它是一个数组,或者至少是一个类似数组的迭代对象
如果不是,则假定需要枚举所有键值对
var obj = {
length:null,
someprop:'some value'
};
obj.length === +obj.length; // false, so do the enumeration
当然,您可以有一个具有length
属性的对象,该属性是一个基本数字,但仍然要枚举这些属性
var obj = {
length: 2,
"prop1":'some value',
"prop2":'some other value'
};
obj.length === +obj.length; // true, it will iterate, but it would
// seem that enumeration is intended
+obj.length
是javascript一元加法运算符。请参阅:因此,该语句是一种检查,以确保obj的length属性实际上是一个数字?语句+obj.length
将obj.length
转换为一个数字
var obj = {
length: 2,
"prop1":'some value',
"prop2":'some other value'
};
obj.length === +obj.length; // true, it will iterate, but it would
// seem that enumeration is intended