Home > Web Front-end > JS Tutorial > body text

Detailed analysis of map() and get() in jQuery

黄舟
Release: 2017-07-19 16:25:03
Original
1552 people have browsed it

There is a concept called "array-like" under jQuery, such as $( " li " ). When a collection is obtained, there will be some attributes of the array, but instancseof Array is still false. But var a=$( "li" )##.get()Process it like this, and theninstancseof Array returns true.

Please note that adding a serial number to var a=$( "li" ).get(1) can get a single element. The nature of these elements is not jQuery objects, but It is a Js object, so jQuery methods cannot be used directly.

The function of map() mainly has two steps. The first step is to traverse, and the second step is to replace.

  $( " li " ).map( function(  ){
    return  $(this).text(  );  // 注意return关键字不可少
} )
Copy after login


The map is traversed first, each item returns a text() value, and then map will These values ​​automatically replace each item value in the $("li") collection, so at this time it is still an array-like (because it is still the shell of $("li")), not a real array. So adding a get() operation later will turn it into a real array, so you can use join(), a method specific to arrays.

Such as:

    $( " li " ).map( function(  ){
        return  $(this).text(  );   
    } ).get(  ).join("%")            // 拼接成字符串,中间用“%”隔开
Copy after login


##Additional:

map() and get() can also directly manipulate the array code as follows:

var arrayObj=["www","xxx","ddd"];
var ww=$.map(arrayObj,function(i){
                      return i;
              }).join(",");
console.log(ww);
var tt=$(":checkbox").map(function(){
                     return this.value;
          }).get().join(",");
console.log(tt);
Copy after login

The above is the detailed content of Detailed analysis of map() and get() in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!