简体   繁体   English

在javascript中在数组内打印对象

[英]print object inside array in javascript

I have an array called list into which I am entering several objects. 我有一个名为list的数组,正在其中输入几个对象。 Each item has a unique id and title. 每个项目都有唯一的ID和标题。

var number = 0;
var list = [];
var item = {};
var i;

var compute = {
    number : 0,
    newItem : function (input) {
        for (i = 0; i < list.length + 1; i++) {
            var item = {
                id: number,
                title: input
            };
        }
        number++;
        list.push(item);
    }
};

and I'm adding data to the array like so: 然后将数据添加到数组中,如下所示:

compute.newItem("Something Important");
compute.newItem("Another thing"); 

I'm trying to print out the contents of this array into an HTML list something like this: 我正在尝试将此数组的内容打印到HTML列表中,如下所示:

<ul id="list">
    <li>Something Important</li>
    <li>Another thing</li>
</ul>

And so on, with each object being printed into its own list element. 依此类推,将每个对象打印到其自己的list元素中。 I'm not sure how to properly print this though? 我不确定如何正确打印此内容? Any thoughts? 有什么想法吗?

I thought something like this might work but I got errors. 我以为这样的事情可能会奏效,但出现错误。

var content;
for (i = 0; i < list.length + 1; i++) {
    content += "<li>" + list[i] + "</li>";
}
document.getElementById("list").innerHTML = content;

The error is: cannot set property 'innerHTML' null 错误是:无法将属性'innerHTML'设置为null

(Note that my javascript may just plain suck...I'm very new to this language.) (请注意,我的JavaScript可能会很烂...我是这种语言的新手。)

The HTML: HTML:

<ul id="list"></ul>

The JavaScript: JavaScript:

var compute = {
    list : [],
    newItem : function (input) {
        this.list.push({
            id : this.list.length,
            title : input
        });
    },
    printList : function (el) {
        var ul;
        ul = el || document.createElement('ul');
        for (i = 0; i < this.list.length; i += 1) {
            ul.innerHTML += '<li>' + this.list[i].title + '</li>';
        }
        return ul;
    }
};

compute.newItem('foo');
compute.newItem('bar');
compute.printList(document.getElementById('list'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM