Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  25] [ 1]  / answers: 1 / hits: 19836  / 12 Years ago, mon, october 1, 2012, 12:00:00

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.


More From » arrays

 Answers
1

JavaScript is not Java - you don't get the length of an array or string by calling its .length() method, but just by retrieving its .length property. The exception which is thrown when you try to invoke the number is what crashes your script and prevents the alert. This would work:



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 ? ']' : );
};


However, you just can use the native .join() method to concatenate the array's values. Also, you should add your methods on the prototype of your Tower objects:



Tower.prototype.printable = function() {
if (this.count)
return [ + this.tower.slice(0, this.count).join(,) + ];
else
return ;
};


Btw: Usually this method is named toString - not only for convenience, but also it would get used when a Tower object is casted to a string value.


[#82814] Saturday, September 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylondaytond

Total Points: 92
Total Questions: 88
Total Answers: 96

Location: China
Member since Fri, Jan 15, 2021
3 Years ago
dylondaytond questions
Tue, Jun 22, 21, 00:00, 3 Years ago
Thu, May 7, 20, 00:00, 4 Years ago
;