返回值:ArrayjQuery.makeArray(obj)
Convert an array-like object into a true JavaScript array.
-
1.2 新增jQuery.makeArray(obj)
obj (Object) Any object to turn into a native Array.
Many methods, both in jQuery and in JavaScript in general, return objects that are array-like. For example, the jQuery factory
function $()
returns a jQuery object that has many of the properties of an array (a length, the []
array access operator, etc.), but is not exactly the same as an array and lacks some of an array's built-in methods (such
as .pop()
and .reverse()
).
Note that after the conversion, any special features the object had (such as the jQuery methods in our example) will no longer be present. The object is now a plain array.
示例:
Turn a collection of HTMLElements into an Array of them.
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<div>First</div>
<div>Second</div>
<div>Third</div>
<div>Fourth</div>
<script>
var elems = document.getElementsByTagName("div"); // returns a nodeList
var arr = jQuery.makeArray(elems);
arr.reverse(); // use an Array method on list of dom elements
$(arr).appendTo(document.body);
</script>
</body>
</html>
演示:
示例:
Turn a jQuery object into an array
jQuery 代码:
var obj = $('li');
var arr = $.makeArray(obj);
结果:
(typeof obj === 'object' && obj.jquery) === true;
jQuery.isArray(arr) === true;