在n个元素之后以块的形式拆分数组

时间:2018-01-10 01:01:32

标签: javascript arrays split

我想在n个部分中拆分一个数组,其中每个部分都打印在一个新行上。 假设我有五个以下需要的数组:

var res = ["dog","bird","cat","bear","cow","fish","ape","worm","ant","fly"];

然后期望的结果应该是:

dog,bird,cat,bear,cow
fish,ape,worm,ant,fly

当我运行此代码时,我似乎只打印了 last 块。

<p id="demo"></p>   
<script>  
    var res = ["dog","bird","cat","bear","cow","fish","ape","worm","ant","fly"];
    var i,j,temparray,chunk = 5;    
    for (i=0,j=res.length; i<j; i+=chunk) {
        temparray = res.slice(i,i+chunk) + "<br>";
        document.getElementById("demo").innerHTML = temparray;
    }  
</script>

4 个答案:

答案 0 :(得分:4)

您必须连接以获取现有的innerHtml

document.getElementById("demo").innerHTML += temparray;

答案 1 :(得分:2)

您忘记在+添加document.getElementById("demo").innerHTML = temparray;

var res = ["dog","bird","cat","bear","cow","fish","ape","worm","ant","fly"];
var i,temparray,chunk = 5;

for (i=0; i < res.length; i+=chunk)
{
  temparray = res.slice(i,i+chunk) + "<br>";
  document.getElementById("demo").innerHTML += temparray;
}  
<p id="demo"></p>   

答案 2 :(得分:1)

仅向innerHTML写入一次更有效,而不是每行输出更新一次(这会强制浏览器在每行之后更新显示)。以下代码段中的for循环只是将每一行追加到temparray变量,而innerHTML只更新一次 - 在for循环之后。

var res = ["dog","bird","cat","bear","cow","fish","ape","worm","ant","fly"];
var i,temparray = "", chunk = 5;

for (i=0; i < res.length; i+=chunk) {
  temparray += res.slice(i,i+chunk) + "<br>";
}
document.getElementById("demo").innerHTML = temparray;
<p id="demo"></p>

答案 3 :(得分:1)

破坏性的while循环方法

var res = ["dog", "bird", "cat", "bear", "cow", "fish", "ape", "worm", "ant", "fly"];
var chunks = [],chunk = 4;
while (res.length) {
  chunks.push(res.splice(0, chunk).join(', '))
}
document.getElementById("demo").innerHTML = chunks.join('<br>');
<p id="demo"></p>