最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Looping through array and output as pairs (divider for each second element) - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked May 28, 2012 at 14:51 mowglimowgli 2,8694 gold badges33 silver badges68 bronze badges
Add a comment  | 

9 Answers 9

Reset to default 7

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'];
}

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);});

Using Array.prototype.reduce():

let pairs = playlist.reduce((list, _, index, source) => {
    if (index % 2 === 0) {
        list.push(source.slice(index, index + 2));
    }
    return list;
}, []);

This gives you a 2-dimensional array pairs to work with.

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];
}
var arr = ["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"];

var group = [];
for (var x = 0; x < arr.length; x += 2) {
    var track = arr[x],
        length = arr[x + 1];
    group.push({
       track: track,
       length: length
    })
}

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 );  
});

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/

Destructive, but clean:

while (arr.length) {
  const Title  = arr.shift();
  const Length = arr.shift();

  // Do work.
}

Not with foreach.

for (var i = 0; i < array.length; i += 2) {
    var name = array[i];
    var time = array[i + 1];
    // do whatever
}
发布评论

评论列表(0)

  1. 暂无评论