I have an array with anonymous elements. Elements are added to the array via php, like so:
$playlist = array();
while (databaseloop) {
$playlist[] = $a_ti
A simple for loop with an increment of two. You might want to make sure that your array length is long enough for i+1, in case the length isn't divisible by 2!
for (i = 0; i+1 < array.length; i+=2) {
name = array[i];
length = array[i+1];
}
Not with foreach
.
for (var i = 0; i < array.length; i += 2) {
var name = array[i];
var time = array[i + 1];
// do whatever
}
as @VisioN said it would be easier if you use associative array or else you can have a separated array of labels while iterating on the client side
var d=["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"] ;
var e=["name","time"];
var c=0;
$.each(d,function(i,j){
if(c>=2)c=0;
console.log(e[c]+j);
c++;
});
http://jsfiddle.net/FmLYk/1/
I would suggest that you optimize your code a little bit more so that it would make a bit more sense and be less error prone, if that's possible that is. This is also a great way to be more object-oriented!
Like this (I'm using jQuery here) :
var array = [ {name: "Hello.mp3", time: "00:00:14"}, {name: "Byebye.mp3", time:"00:00:30"}, {name: "Whatsup.mp3", time: "00:00:07"}, {name: "Goodnight.mp3", time: "00:00:19"}];
Then you would be able to loop over it and produce a bit more clean looking code
array.forEach(function(data){
//edit the output here
console.log(data.name + " " + data.time );
});
You could split the array into an array of two-element arrays.
var arr = ["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"];
arr.map(function(elem,i,arr){return [elem, (i+1<arr.length) ? arr[i+1] : null];})
.filter(function(elem,i){return !(i%2);});
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'];
}