jQuery provides two methods to convert map into a string array: jQuery.map() and Array.prototype.map(). Below are their usage and examples.
jQuery.map() method to convert an array or object into another array. It applies a callback function to each element of the original array and builds a new array using the contents returned by the callback function.
Example:
var obj = {one:1, two:2, three:3, four:4, five:5}; var arr = jQuery.map(obj, function(val, key){ return [key, val]; }); console.log(arr); // [["one",1], ["two",2], ["three",3], ["four",4], ["five",5]]
In the above example, we convert an object into an array consisting of an array of key-value pairs. The callback function accepts two parameters, the first parameter is the value and the second parameter is the key. We combine them to return an array and collect them to build a new array.
The Array.prototype.map() method is similar to the jQuery.map() method, and also converts one array to another An array, but it's a method on the array prototype, not a jQuery method.
Example:
var arr = [1,2,3,4,5]; var newArr = arr.map(function(val){ return val * 2; }); console.log(newArr); // [2, 4, 6, 8, 10]
In this example, we convert an array of numbers into a new array where each element in the new array is twice the size of the corresponding element in the original array.
Summary
Use jQuery.map() or Array.prototype.map() to convert a map into a string array. Their usage is similar, except that one is a jQuery method and the other is an Array prototype method. You can choose the appropriate method according to your situation.
The above is the detailed content of How to convert map to string array in jquery (two methods). For more information, please follow other related articles on the PHP Chinese website!