Jan 022013
 

Una funzione di jQuery per manipolare gli array è map().

map() dovrebbe essere utilizzato al posto di each ogni volta che vogliamo restituire un array, per esempio per convertirlo in una stringa JSON.

Iniziamo dall’html:

<!DOCTYPE html>
<html lang="it">
<head>
<title>La funzione map()</title>
</head>
<body>
<h2>Esempio d'uso della funzione map()</h2>
<p id="before">Prima di map():</p>
<p id="after">Dopo map():</p>
</body>
</html>

Nel codice javascript prepariamo un array e lo stampiamo come JSON,

successivamente lo manipoliamo con map() e lo ristampiamo sempre con JSON


<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function() {
var arr = [1, 2, 3, 4, 5];
$('#before').append(JSON.stringify(arr));
arr = $.map(arr, function(value, index) {
return 'fai qualcosa con ' + value;
});
$('#after').append(JSON.stringify(arr));
});
</script>

L’esempio

Sorry, the comment form is closed at this time.