循环遍历数组并作为对输出(每个第二个元素的分隔符)

时间:2012-05-28 14:51:13

标签: javascript jquery arrays foreach

我有一个包含匿名元素的数组。元素通过php添加到数组中,如下所示:

$playlist = array();

while (databaseloop) {
  $playlist[] = $a_title;
  $playlist[] = $a_length;
}

echo json_encode(array('playlist'=>$playlist));

所以数组变为:

["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"] and so on

然后我用ajax post在jquery中检索这个数组。一切正常。

现在,我正在寻找一种在javascript / jquery中将所有数组元素作为对处理/输出的方法。为每个第二个元素“做点什么”。像这样:

foreach (two_elements_in_array) {
  // output track name
  // output track time
  // output some divider
}

如何做到这一点?

9 个答案:

答案 0 :(得分:6)

嗯,也许这是最基本的解决方案:

for (var i = 0; i < arr.length; i += 2) {
    var title = arr[i];
    var len = arr[i+1];
}

但是,我建议您按如下方式安排$playlist

while (databaseloop) {
    $playlist[] = array(
        "title" => $a_title,
        "length" => $a_length
    );
}

然后,只需使用:

即可轻松迭代元素
for (var i = 0; i < arr.length; i++) {
    var title = arr[i]['title'];
    var len = arr[i]['length'];
}

答案 1 :(得分:2)

您可以将数组拆分为两元素数组的数组。

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

答案 2 :(得分:1)

使用Array.prototype.reduce()

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

这为您提供了一个可以使用的二维数组pairs

答案 3 :(得分:0)

不在foreach

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

答案 4 :(得分:0)

一个简单的for循环,增量为2。您可能希望确保您的数组长度足够长,以便i + 1,以防长度不能被2整除!

for (i = 0; i+1 < array.length; i+=2) {
  name = array[i];
  length = array[i+1];
}

答案 5 :(得分:0)

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

答案 6 :(得分:0)

正如@VisioN所说,如果你使用关联数组会更容易,否则你可以在客户端迭代时拥有一个独立的标签数组

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/

答案 7 :(得分:0)

我建议您稍微优化一下代码,以便它更有意义,更容易出错,如果可能的话。 这也是更加面向对象的好方法!

像这样(我在这里使用jQuery):

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

然后你就可以遍历它并产生更干净的代码

array.forEach(function(data){
    //edit the output here
    console.log(data.name + " " + data.time );  
});

答案 8 :(得分:0)

破坏性,但干净:

S-