For循环数组只显示最后一个值 [英] For loop through Array only shows last value

查看:92
本文介绍了For循环数组只显示最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历一个数组,然后使用 innerHTML 为数组中的每个条目创建一个新的

  • 元素.不知何故,我的代码只显示数组中的最后一个值.我已经坚持了几个小时,似乎无法弄清楚我做错了什么.

    I'm trying to loop through an Array which then uses innerHTML to create a new

  • element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.

    window.onload = function() {
    
    // Read value from storage, or empty array
    var names = JSON.parse(localStorage.getItem('locname') || "[]");
    var i = 0;
    
        n = (names.length);
        for (i = 0; i <= (n-1); i++) {
            var list = names[i];
            var myList = document.getElementById("list");
            myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
        }
    }
    

    我的 HTML 中有一个带有 id 'list' 的 UL.

    I have a UL with the id 'list' in my HTML.

    推荐答案

    改变你的 for 循环:

    for (i = 0; i <= (n-1); i++) {
        var list = names[i];
        var myList = document.getElementById("list");
        myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
    }
    

    使用 += 而不是 =.除此之外,您的代码看起来不错.

    Use += instead of =. Other than that, your code looks fine.

    这篇关于For循环数组只显示最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆