printing array values in js

user1545072 picture user1545072 · Oct 1, 2012 · Viewed 19k times · Source

I'm trying to create a function that will run through an array and collect it's value to a string that looks like this: '[1,2,3]'. I also need it to present only part of the array in some cases, according to a given index. For example: the array [1,2,0] printed from index 0 to index 1 will look like this: '[1,2]'. For some reason my function don't give any output at all. Here it is:

function Tower(size, isFull) {
    this.count = 0;
    this.tower = new Array(size);

    this.add = function(disk) {
        this.tower[this.count++] = disk;
    };

    if (isFull) {
        for (var i = 1; i <= size; i++) {
            this.add(i);
        };
    }

    this.canAdd = function(disk) {
        return this.count == 0 || this.tower[this.count - 1] > disk;
    };

    this.getTopDiskValue = function() {
        return (this.count > 0) ? this.tower[this.count - 1] : 0;
    };

    this.popTop = function() {
        return this.tower[--this.count];
    };

    this.isFull = function() {
        return this.count == this.tower.length;
    };

    this.printable = function() {
        var output = "[";
        for (var i = 0; i < this.count; i++) {
            output += "" + this.tower[i] + ',';
        }
        return output.substring(0, output.length() - 1) + (output.length() > 1 ? ']' : "");
    };
}

I expect the printable() function to return the string so that the code:

var tower = new Tower(3,true);
alert(tower.printable());

will pop an alert box with the text '[1,2,3]' on it. This object is a translation from Java. It worked great in java btw, I guess the translation is not perfect.

Answer

Denys S&#233;guret picture Denys Séguret · Oct 1, 2012

What you do is much too complicated.

Let's say you have an array declared as

var array = [1, 2, 3];

you get the desired string with

return '['+array.join(',')+']';

You don't need pop or add functions, they're also native (and heavily optimized) :

var last = array.pop()
array.push(newItem);

Reference :

Note that all browsers offer a console, in which you'll find a detailed explanation of your errors. Have a look for example at the Chrome Developer Tools.