douzuo5504 2012-12-10 08:39
浏览 46
已采纳

Javascript - 在FOR LOOP中以特定间隔执行某些操作

I got a problem while developing javascript based idea..

Here's the main code,

 $.post("datainlines.php", function(data) { 

        var lines = data.split("
");

           for (var i = 1; i < lines.length; i++) {

             sitename= lines[i]; sitetype=lines[i++]; 

             if(i/2 == '0'){ alert current values in sitename and sitetype variables}

            }

       } );

This will get data in datainlines.php via POST, datainlines.php file data structure is like this -

Google
search
Stackoverflow
Questions
Yahoo
search
Facebook
social network

How to get site name and type in groups, like

Google
search 

then

Stackoverflow
questions

is there anyway to group out and alert per every two loops in for loop ?

  • 写回答

1条回答 默认 最新

  • douye2020 2012-12-10 08:42
    关注

    Increment your loop value by two:

    $.post("datainlines.php", function(data) {
    
        var lines = data.split("
    ");
    
        for (var i = 1; i < lines.length; i+=2) {
            sitename = lines[i];
            sitetype = lines[i+1];
            alert(sitename + " " + sitetype);
        }
    });​
    

    Note the i+=2 in the for loop. This will skip every other entry in the array.


    As an aside, I think with this line:

    if(i/2 == '0')
    

    What you were actually looking for is the modulus:

    if(i % 2 === 0)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法