简体   繁体   中英

print object inside array in javascript

I have an array called list into which I am entering several objects. Each item has a unique id and title.

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:

<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. 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

(Note that my javascript may just plain suck...I'm very new to this language.)

The HTML:

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

The 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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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