Home  >  Article  >  Web Front-end  >  Detailed explanation of the difference between .toArray() and .makeArray() in jQuery

Detailed explanation of the difference between .toArray() and .makeArray() in jQuery

黄舟
黄舟Original
2018-05-14 10:29:082161browse

According to jQuery documentation:

toArray() returns an array containing all DOM elements in the collection of jQuery objects (this method accepts no parameters) . This method extracts the members of this group of DOM elements into a JavaScript Array:

jQuery('.some-class').toArray() -> [ dom_el_1, dom_el_2, dom_el_3, ... ]

alert($('li').toArray());   //  .toArray() 返回jQuery集合中所有元素

makeArray (this is the "static method" of the jQuery object) using an array-like object (jQuery, arguments, nodeList ,...) and construct a proper JavaScript array from it, so Array's methods can be called on the result:

// returns a nodeList (which is array like item) but not actual array// you can't call reverse on intvar elems = document.getElementsByTagName("p"); 
var arr = jQuery.makeArray(elems);
arr.reverse(); // use an Array method on list of dom elements$(arr).appendTo(document.body);

In short, toArray Set jQuery elements to javascript Array, makeArrayConvert any array of similar objects to javascript Array.

The above is the detailed content of Detailed explanation of the difference between .toArray() and .makeArray() in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn