[英]I am trying to print perimeter of defined polygons with the help of class but it is giving me undefined as an output please tell me where the problem
I am getting undefined as output please tell me to resolve this and tell me where the problem is.我越来越未定义为 output 请告诉我解决这个问题并告诉我问题出在哪里。
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.您必须在使用构造函数中声明的变量时使用此关键字,并且要在 x 中添加值,您必须将 0 分配给 x 并且 i 将小于数组的长度,否则它将仅返回 0。最后您必须删除这行 x = values[i] 因为它将在循环的每次迭代中重新分配 x 的值。
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.