I am trying to create a function that will be run through an array and get its value for a string that looks like this: '[1,2,3]'. I also need it to represent only part of the array in some cases, according to the given index. For example: an array [1,2,0], printed from index 0 to index 1, would look like this: '[1,2]'. For some reason, my function does not give any output at all. Here he 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 a string so that the code:
var tower = new Tower(3,true); alert(tower.printable());
a warning window appears with the text '[1,2,3]' on it. This object is a translation from Java. It worked perfectly in java btw, I think the translation is not perfect.
user1545072
source share