I have an array with anonymous elements. Elements are added to the array via php, like so:
$playlist = array();
while (databaseloop) {
$playlist[] = $a_title;
$playlist[] = $a_length;
}
echo json_encode(array('playlist'=>$playlist));
So the array becomes:
["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"] and so on
Then I retrieve this array in jquery with ajax post. All that works fine.
Now, I'm looking for a way to treat/output all array elements as pairs in javascript/jquery. "do something" for each second element. Like this:
foreach (two_elements_in_array) {
// output track name
// output track time
// output some divider
}
How can this be done?
To get the second to last element in an array, use bracket notation to access the array at index array. length - 2 , e.g. arr[arr. length - 2] . The last element in an array has an index of array.
A for loop can be used to access every element of an array. The array begins at zero, and the array property length is used to set the loop end.
Using forEach loop forEach loop is a modern way to loop through the array. Also, it gives more flexibility and control over the array and elements.
While a traditional for loop often loops through an array, it uses an index to do so, making Option B incorrect. The for-each loop goes through each element, storing it in a variable. Option C is correct.
Well, maybe this is the most basic solution:
for (var i = 0; i < arr.length; i += 2) {
var title = arr[i];
var len = arr[i+1];
}
However, I would recommend you to arrange $playlist
as follows:
while (databaseloop) {
$playlist[] = array(
"title" => $a_title,
"length" => $a_length
);
}
Then it will be easy to iterate the elements simply with:
for (var i = 0; i < arr.length; i++) {
var title = arr[i]['title'];
var len = arr[i]['length'];
}
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