I am using the .map function to convert elements to an array, and I'd like to then convert this array into a string:
javascript:
var selectedElements = $('.data').map(function() {
return $(this).hasClass('selected') ? 'true' : 'false';
});
var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
A = A + "";
var string = selectedElements + "";
console.log("\ndebug:");
console.log(selectedElements);
console.log(A);
console.log(string );
html:
<div class='data'></div>
<div class='data selected'></div>
<div class='data selected'></div>
<div class='data'></div>
<div class='data'></div>
<div class='data'></div>
<div class='data'></div>
Console output:
debug: fiddle.jshell.net:29
["false", "true", "true", "false", "false", "false", "false"]
Sunday,Monday,Tuesday,Wednesday,Thursday
[object Object]
Fiddle here: http://jsfiddle.net/F8ufE/
How do I convert the selectedElements to array ?
Below are the various methods to convert an Array to String in Java: Arrays. toString() method: Arrays. toString() method is used to return a string representation of the contents of the specified array.
JavaScript Array toString() The toString() method returns a string with array values separated by commas.
Return Value: It returns a new array and elements of arrays are result of callback function. Below examples illustrate the use of array map() method in JavaScript: Example 1: This example use array map() method and return the square of array element.
map() method applies a function to each item in an array or object and maps the results into a new array. Prior to jQuery 1.6, $. map() supports traversing arrays only.
According to the .map()
docs:
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.
So if you want to get the actual array you can use get
method, like this:
var selectedElements = $('.data').map(function() {
return $(this).hasClass('selected') + "";
}).get();
For converting an array to a string you can use join
method:
selectedElements = selectedElements.join()
Use the jQuery function .makeArray like so:
var selectedElements = $.makeArray($('.data').map(function() {
return $(this).hasClass('selected') ? 'true' : 'false';
}));
var A = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
A = A + "";
var string = selectedElements + "";
console.log("\ndebug:");
console.log(selectedElements);
console.log(A);
console.log(string);
http://jsfiddle.net/U5LTK/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With