【问题标题】:For loop only outputs last elementFor 循环仅输出最后一个元素
【发布时间】:2016-02-15 09:33:49
【问题描述】:

对不起,如果重复但似乎无法在任何地方找到正确的答案: 在 console.log 中输出是正确的,但在屏幕上它只显示数组的最后一个元素

    {id: 3, naam: "Besured", type: "Voor alle pakketten geldt:, Ready-2-go ,Love-2-move, Alles-in-1 ", vergoeding:"Registratie bij koepel vereist , Geen vergoeding, Geen vergoeding, 80% tot € 200 per jaar maximaal € 50 per consult"},

            var string = test[i].type;
            var thisString = string.split(",");


        for(var j=0; j<thisString.length;j++){
                console.log(thisString[j]);
                $('.first')[0].innerHTML = thisString[j];
                $('.second')[0].innerHTML = thisString[j];
                $('.third')[0].innerHTML = thisString[j];
                $('.fourth')[0].innerHTML = thisString[j];
            }

【问题讨论】:

  • 嗯,很明显,当您将某个值设置为某个值,然后立即将其设置为另一个值时,就会发生这种情况。
  • 期望会做什么......?!
  • 我想在第一类显示数组的第一个元素,第二类显示第二个元素等
  • $('.first')[0].innerHTML = thisString[0]; $('.second')[0].innerHTML = thisString[1]; ... 看,没有循环!
  • 但不是全部都填满了,如果是空的我不想输出。

标签: javascript for-loop


【解决方案1】:

你的评论说

我需要在数组的第一个元素中第一类,第二类 二等舱物品等

那就试试

    $('.first').html( trimStr( thisString[0] ) ); 
    $('.second').html( trimStr( thisString[1] ) );
    $('.third').html( trimStr( thisString[2] ) );
    $('.fourth').html( trimStr( thisString[3] ) );

function trimStr( input ) {

    if (typeof input === 'undefined' || input == null) 
    {
        input =  "";
    }

    return input.trim();
}

【讨论】:

  • 如果我执行 += 它会显示每个类中数组中的所有项目。我需要在第一类中的数组的第一个元素,第二类中的第二项等
  • 但不是全部都填满了,如果是空的我不想输出。
  • @ElonGielink 即使它是空的,您元素的 innerHTML 也会保持为空。所以不用担心空元素
  • @Elon 那么,在某处输入if (thisString[0]) 以检查是否要输出它。真的,为了获得一种更优化的方法来生成优雅的代码,我们需要知道你到底想在这里做什么。
  • 如果我这样做,它会说“未定义”,因为如果数组中有 3 个元素并且我调用 7 个元素,则数组中没有元素(并非所有数组的长度都相同,这就是我使用的原因数组长度)
猜你喜欢
  • 2019-10-22
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 2020-11-22
  • 2019-01-01
相关资源
最近更新 更多