Javascript循环意外行为

时间:2014-12-21 15:33:08

标签: javascript loops for-loop

这是我的功能,它应该以每组5行的形式打破字符串,但不知何故循环显示意外行为,警报(数据)打印4而不是5个字符串。阿米我在这里错过了什么?

function returnwasset(somedata) {
    alert(somedata);
    var lines = somedata.split('\n');
    var counter = 1;
    var data = "";
    for (var i = 0; i < lines.length; i++, counter++) {
        if (counter % 5 === 0) {
            alert(data);
            data = "";
            counter = 1;
        }
        data = data + "\n" + lines[i];
    }
}

5 个答案:

答案 0 :(得分:0)

将您的代码更改为:

data=data+"\n"+lines[i];
if(counter%5===0)
{
    alert(data);
    data="";
    counter=1;
}

因此,您首先附加数据,然后显示该数据。一旦循环退出,你应该检查计数器变量的最后几行小于5,如:

if (counter < 5) {
    alert(data);
}

答案 1 :(得分:0)

尝试使用以下函数以预定义的数字显示字符串。的线条。它将你的完整字符串分成五行。

function returnwasset(somedata){
    var lines = str.split(' ');
    var wordsperline = parseInt(lines.length / 5);
    var finalline = parseInt(lines.length % 5);
    //alert(lines.length);
    var result = "";
    var counter = 0;
    for(var i = 0; i < 5; i++){
        if(i != 4){
            for(var j = 0; j < wordsperline; j++){
                result += lines[counter] + " ";
                counter++;
            }
            result += "\n";
        }
        else{
            for(var k = 0; k < (wordsperline + finalline); k++){
                result += lines[counter] + " ";
                counter++;
            }          
        }
    }

    alert(result);
}

jsFiddle

答案 2 :(得分:0)

您不需要额外的counter,您可以使用迭代索引进行数学运算。

&#13;
&#13;
var testData = '013192002197143 012419001189107 012419002540761 012420002277776 012421009834353 013192002197143 012419001189107 012419002540761 012420002277776 012421009834353'.split(' ').join("\n");

function returnwasset(somedata) {
  alert(somedata);

  var lines = somedata.split("\n");
  var data = "";

  for(var i = 0; i < lines.length; i++) {
    data += lines[i] + "\n";

    if(i % 5 === 4) {
        alert(data);
        data = "";
    }
  }
}

returnwasset(testData)
&#13;
&#13;
&#13;

答案 3 :(得分:0)

错误原因是当第五个循环结束时counter值变为2,因为计数器在每个循环后递增,所以只需要counter = 0如果条件得到满足。因此,当第五个循环结束时,counter将为值1: -

var a = '013192002197143\n012419001189107\n012419002540761\n012420002277776\n012421009834353\n013192002197143\n01241900118910\n012419002540761\n012420002277776\n012421009834353';


function returnwasset(somedata) {
    alert(somedata);
    var lines = somedata.split('\n');
    var counter = 1;
    var data = "";
    for (var i = 0; i < lines.length+1; i++, counter++) {
        data = data + "\n" + lines[i];
        if (counter % 5 === 0) {
            alert(data);
            data = "";
            counter = 0;
        }        
    }
}

window.onload = returnwasset(a);

答案 4 :(得分:0)

这是一种扩展了阿尔玛思想的方法,并且在循环之后消除了对counter变量或额外代码的需求。

只需将for循环替换为:

for (var i = 0; i < lines.length; i++) {
    data += lines[i] + "\n";
    if ((i % 5 === 0 && i > 0) || (i + 1) === lines.length) {
        alert(data);
        data = "";
    }
}