我刚刚浏览了jquery的源代码并遇到了以下函数:
function isArraylike( obj ) {
// Support: iOS 8.2 (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
如果你逐行,你会看到jquerys内部方法被调用,如$.type
和$.isWindow
,现在我不明白的部分就在最后,以下代码:
( length - 1 ) in obj;
我看到最后使用的&&
,唯一的问题是这个检查何时返回true,何时返回false?真的很难说,只检查obj
是一个对象还是obj
是一个数组?
检查真的检查是什么?
我创建了以下代码片段,以便了解该行:
arr = ['hello' , 'world'];
check = (arr - 1) in arr;
console.log(check);
我在控制台中得到一个假,我不知道什么情况会返回true
。有人可以对此有所了解吗?
答案 0 :(得分:2)
这很简单,但与jquery无关。那只是javascript。 它检查密钥是否是对象或数组的一部分。
var a=["a","b","c","d"]
至少有四个键0,1,2和3,因此您可以正确测试所有这些键,即在控制台中
0 in a
true
1 in a
true
2 in a
true
3 in a
true
4 in a
false
因此(length-1) in obj
检查是否定义了数组或对象的最后一个元素。
已完成,因为您可以将a
定义为
var a={ "0":"a", "3":"d", "length":4 }
这将是一个稀疏数组。
您的测试代码将是
arr = ['hello' , 'world'];
check = (arr.length - 1) in arr;
console.log(check);