![](/img/trans.png)
[英]I am running this javascript code but it is giving me an.. error please tell me what is wrong because I think the code is correct?
[英]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
我越來越未定義為 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());
您的代碼中有錯誤。 檢查此代碼並正確調試。
...
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;
}
}
...
您必須在使用構造函數中聲明的變量時使用此關鍵字,並且要在 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.