Home >Web Front-end >JS Tutorial >Detailed analysis of map() and get() in jQuery
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关键字不可少 } )
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("%") // 拼接成字符串,中间用“%”隔开
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);
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!