I am getting undefined as output please tell me to resolve this and tell me where the problem is.
class Polygon { constructor(side) { this.values = side; } perimeter() { var x; for (var i = 0; i > this.values.length; i++) { x = values[i]; x += values[i]; } return x; } } var triangle = new Polygon([3, 4, 5]); const rectangle = new Polygon([10, 20, 10, 20]); const square = new Polygon([10, 10, 10, 10]); const pentagon = new Polygon([10, 20, 30, 40, 43]); console.log(rectangle.perimeter()); console.log(square.perimeter()); console.log(pentagon.perimeter());
You have bugs in you code. Check this code and debug properly.
...
perimeter(){
var x = 0; // Initialize x to zero when begin
for (var i = 0 ; i < this.values.length; i++){ // change greaeter than ( > ) symbol to less than symbol ( < )
// x = values[i]; // remove this line
x += this.values[i]; // put this keyword to infront
}
return x;
}
}
...
You have to use this keyword while using the variable declared in the constructor and for adding values in x you have to assign 0 to x and i will be less than the length of the array else it will return just 0. Lastly you have to remove this line x = values[i] because it will reassign the value of x on each iteration of the loop.
class Polygon {
constructor(side) {
this.values = side;
}
perimeter() {
var x = 0;
for (var i = 0; i < this.values.length; i++) {
x += this.values[i];
}
return x;
}
}
var triangle = new Polygon([3, 4, 5]);
const rectangle = new Polygon([10, 20, 10, 20]);
const square = new Polygon([10, 10, 10, 10]);
const pentagon = new Polygon([10, 20, 30, 40, 43]);
console.log(rectangle.perimeter());
console.log(square.perimeter());
console.log(pentagon.perimeter());
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.