Use jQuery. makeArray () to convert multiple types into JS native arrays, jquery. makearray

Source: Internet
Author: User

Use jQuery. makeArray () to convert multiple types into JS native arrays, jquery. makearray

The jQuery. makeArray (obj) function can easily guess its purpose from the name: it should be used to convert the passed object into a native array

Let's look at the explanation on the official website:Convert an array-like object into a true JavaScript array.(Convert an array object similar to a JS native array)

So what kind of object can be called "array-like object? I am not eager to answer this question. I believe you will understand it after reading the article. First, let's take a look at the experiment below.

Convert HTMLCollection to native Array

<!doctype html>

Here we can see that in chrome, A HTMLCollection is returned through document. getElementsByTagName ("div ")

Instead of the NodeList mentioned on the official website, I found the difference between NodeList and HTMLCollection:HTMLCollection objects and NodeList objects are very similar, but the former may be able to use both name indexes and digital indexes, while the latter can only use digital indexes for access (of course, NodeList is also "array-like object ")

Experiment shows that elems can be indexed by name and array. Conclusion: In chrome, document. getElementsByTagName ("div") returns an HTMLCollection.

HTMLCollection can get its length through elems. length, and can access the elements in it through elems [0 ].

Does it look like an array access method? In fact, it is just an "Array-like object", but it is not a native array of js, so it cannot access the native method of Array, such (. pop () and. reverse ())

Later, the native JS array arr will be obtained through jQuery. makeArray (elems) conversion. Next we can use the native method of array!


Convert the Array wrapped in jQuery into a native Array

In addition to HTMLCollection, what can be converted? Have you heard of the array of jQuery packages?

But it must have been used. For example, if you get a group of divs through $ ('div '), this group of divs is an array of jQuery packages.

For example. the map () function also obtains an array wrapped in jQuery. You can also get the length by using the length index and access the array wrapped in jQuery through the subscript index. In addition, you can also use the method provided by jQuery.

You can use $. makeArray (obj) to convert it to a native Array. For example, the most common jQuery array obtained in the. map () function is converted to a native Array and then the result is obtained through join ().

Of course, there are more than one method to convert the array wrapped in jQuery into a native array. Common methods include. get () and. toArray ()


Convert a json object to a native Array
This situation is a little more complicated, because the json object is not "array-like object", so we need a type of conversion

Do you still remember the "array-like object" we mentioned before? They can all get the length through. length and can be accessed through subscript indexes, such as: fakeArr. length, fakeArr [0]

So can we convert json into "array-like object" by making it support?

First design:

To make json support fakeArr. length simple, you only need to define a key-value pair whose key is length.

Supporting subscript access also seems to be easy to solve. In addition, key-value pairs use numbers as keys ~

Try:

Var fakeArray = {0: "Zhang San", 1: "Li Si", 2: "zhu liu", length: 3}; var realArray = $. makeArray (fakeArray); console. log (fakeArray) console. log (realArray) realArray. reverse (); console. log (realArray );

Have you seen it? Successful! The realArray here is already the native array of js, so you can use native methods such as reverse ()

Note thatIn the conversion process, length is very important. This length determines the length of the converted array.

If the length in the preceding example is set to 2, the converted array contains only the first two elements, namely ["Zhang San", "Li Si"].

If the length in the preceding example is set to 4, the converted Array is not the expected Array, but an Array similar to new Array (). push (fakeArray ).


Call the java function in js to return the arraylist type. How can I convert it to the array type in js?

Js only has the var type, regardless of the Low-hour group or other types similar to the String or int type in java. If js wants to obtain the array in ava, use json.
Convert a set to json in java code:
@ RequestMapping (value = "/slick/home ")
Public void homePage (HttpServletResponse response) throws IOException {
String json = null;
Response. setContentType ("application/json ");
PrintWriter out = response. getWriter ();
Gson gson = new GsonBuilder (). serializeNulls (). setDateFormat (DateFormat. LONG)
. SetPrettyPrinting (). setVersion (1.0). create ();
List <Integer> list = new ArrayList <Integer> ();
For (int I = 0; I <10; I ++ ){
List. add (I );
}
JSONArray ja = JSONArray. fromObject (mes );
Json = gson. toJson (ja. toString ());

Out. print (json );
}

Code parsed in js:
Function tested (){
JQuery. getJSON ("$ {path}/slick/home? Time = "+ new Date (). getTime (),
Function (items ){
Var output = [];
Output. push ('<option value = "">-select-</option> ');
JQuery. each (items, function (I, item ){
Output. push ('<option value = "' + item + '">' + item + '</option> ');
});
('{'{Nextunit}.html (output. join (''));
Certificate ('{'{nextunit}.css ('display ','');
});
}

Hope to help you.

Call the java function in js to return the arraylist type. How can I convert it to the array type in js?

JsList: Your arrylist
<Script type = "text/javascript">

Function initPages ()
{
Var codes = new Array ();

// Convert the array in JAVA into an array in JS
<%
If (jsList! = Null)
{
For (int I = 0; I <jsList. size (); I ++)
{
%>
Codes [<% = I %>] = '<% = jsList. get (I) %> ';
<%}
}
%>

</Script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.