This article is currently in the process of being translated into Vietnamese (~17% done).
The toArray() and makeArray() methods
Trong bài trước chúng ta đã xem cách lặp qua các thành phần jQuery với each(), nhưng nếu bạn cần làm gì đó với vòng lặp JavaScript thì làm cách nào? Trong trường hợp này, phải chuyển nhóm các đối tượng jQuery sang mảng. Như vậy ta có thể áp dụng một số hàm như reverse() chẳng hạn.
The toArray() method
Let's jump straight to an example, where we use the toArray() method to take a collection of list item elements we just selected and turn them into a JavaScript array:
<ul id="toArrayTest">
<li>John Doe</li>
<li>Jane Doe</li>
<li>Joe Doe</li>
</ul>
<script type="text/javascript">
$(function()
{
var arrayOfNames = $("ul#toArrayTest li").toArray();
arrayOfNames.reverse();
for(var i = 0; i < arrayOfNames.length; i++)
{
$("ul#toArrayTest").append("<li>" + arrayOfNames[i].innerText + "</li>");
}
});
</script>
As you can see, once we have the arrayOfNames, we call the reverse() method on it. Then we loop through it and append each name to the source list, but this time in the reverse order. All of this is basically just to show you how easy it is to use the toArray() method!
The makeArray() method
The makeArray() method allows you to take something that behaves like an array, but isn't, and turn it into an array. A great example of this is the jQuery object, returned by many jQuery methods. It's like an array, because it has a length property and you can iterate through it with the each() method, but that doesn't make it a native JavaScript array. This is also true for some methods in native JavaScript, like the getElementsByTagName() and getElementByClassName() methods, which returns a NodeList object.
<ul id="makeArrayTest">
<li class="testItem">John Doe</li>
<li class="testItem">Jane Doe</li>
<li class="testItem">Joe Doe</li>
</ul>
<script type="text/javascript">
$(function()
{
var arrayOfItems = $.makeArray(document.getElementsByClassName("testItem"));
arrayOfItems.reverse();
for(var i = 0; i < arrayOfItems.length; i++)
{
$("ul#makeArrayTest").append("<li>" + arrayOfItems[i].innerText + "</li>");
}
});
</script>
Here we use a combination of native JavaScript and jQuery to demonstrate how the makeArray() method works. As soon as we have a NodeList containing the desired list items, we can turn it into an array with the makeArray() method and then work with it like a native JavaScript array, much like we did in the first example.
Summary
In this article, we have learned more about another couple of nice utility methods from the jQuery framework. They don't do anything you can't do with plain JavaScript, but they do it with much less code!