jQuery源码分析-03构造jQuery对象-工具函数

2020-05-19 07:26:09易采站长站整理

if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
// 没有参数args则调用,则调用call,上下文设置为当前遍历到的对象,参数设置为key/index和value
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
// 尽可能的使用本地String.trim方法,否则先过滤开头的空格,再过滤结尾的空格
trim: trim ?
function( text ) {
return text == null ?
“” :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
“” :
text.toString().replace( trimLeft, “” ).replace( trimRight, “” );
},
// results is for internal usage only
// 将伪数组转换为数组
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have ‘length’
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
// 一大堆浏览器兼容性测试,真实蛋疼
var type = jQuery.type( array );
// 测试:有没有length属性、字符串、函数、正则
// 不是数组,连伪数组都不是
if ( array.length == null
|| type === “string”
|| type === “function”
|| type === “regexp”
|| jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
// $.type( $(‘div’) ) // object
jQuery.merge( ret, array );
}
}
return ret;
},
//
inArray: function( elem, array ) {
// 是否有本地化的Array.prototype.indexOf
if ( indexOf ) {
// 直接调用Array.prototype.indexOf
return indexOf.call( array, elem );
}
// 遍历数组,查找是否有完全相等的元素,并返回下标
// 循环的小技巧:把array.length存放到length变量中,可以减少一次作用域查找
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
// 如果返回-1,则表示不在数组中
return -1;
},
// 将数组second合并到数组first中
merge: function( first, second ) {
var i = first.length, //
j = 0;
// 如果second的length属性是Number类型,则把second当数组处理
if ( typeof second.length === “number” ) {