makeArray(obj)
概述
将类数组对象转换为数组。
类数组对象共性有 2点:
1.拥有 length属性。
2.可以通过下标来访问元素。
类数组对象相较于数组,少了很多便捷的API,因此很多框架提供了转换方法。
最简便的方法,是利用 Array.prototype上的 slice方法:
function makeArray(array){ return Array.prototype.slice.call(array); }
类数组对象有 length 属性,其成员索引为 0 至 length - 1。实际中此函数在 jQuery 中将自动使用而无需特意转换。
参数
obj Object
类数组对象。
过滤数组中小于 0 的元素。
FirstSecondThirdFourth
var arr = jQuery.makeArray(document.getElementsByTagName("div"));
arr.reverse(); // 使用数组翻转函数
Fourth
Third
Second
First
inArray(value,array,[fromIndex])
概述
确定第一个参数在数组中的位置,从0开始计数(如果没有找到则返回 -1 )。
参数
value,array,[fromIndex] Any,Array,Number
value:用于在数组中查找是否存在
array:待处理数组。
fromIndex:用来搜索数组队列,默认值为0。
array Array
待处理数组。
查看对应元素的位置
var arr = [ 4, "Pete", 8, "John" ];
jQuery.inArray("John", arr); //3
jQuery.inArray(4, arr); //0
jQuery.inArray("David", arr); //-1
jQuery.inArray("Pete", arr, 2); //-1
toArray()
概述
把jQuery集合中所有DOM元素恢复成一个数组。
得到所有li的元素数组
alert($('li').toArray());
[, ]
jquery源码
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + (version + Math.random()).replace(/\D/g, ""),
// Assume jQuery is ready without the ready module
isReady: true,
// results is for internal usage only
makeArray: function (arr, results) {
var ret = results || [];
if (arr != null) {
if (isArraylike(Object(arr))) {
jQuery.merge(ret,
typeof arr === "string" ?
[arr] : arr
);
} else {
push.call(ret, arr);
}
}
return ret;
},
inArray: function (elem, arr, i) {
var len;
if (arr) {
if (indexOf) {
return indexOf.call(arr, elem, i);
}
len = arr.length;
i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
for (; i < len; i++) {
// Skip accessing in sparse arrays
if (i in arr && arr[i] === elem) {
return i;
}
}
}
return -1;
}
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function () {
return slice.call(this);
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function (elems) {
// Build a new jQuery matched element set
var ret = jQuery.merge(this.constructor(), elems);
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
slice: function () {
return this.pushStack(slice.apply(this, arguments));
}
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};