尋找確定形狀類型的邊(數)傳入..下面的代碼只去第一個索引,三角形..我的猜測是因爲我沒有正確比較邊數數組中的屬性?我試着用filter
,forEach
和map
跑進兔子洞。先謝謝您的幫助。努力比較邊數量來確定形狀類型
var Shape = function(sides) {
this.sides = sides;
if (this.sides < 3 || typeof(this.sides) !== 'number'){
this.sides = null;
}
};
Shape.prototype.getType = function(sides){
var shapes = [{type: "triangle", sides: 3}, {type: "quadrilateral", sides: 4}, {type: "pentagon", sides: 5}, {type: "hexagon", sides:6}, {type: "heptagon", sides: 7}, {type: "octagon", sides: 8}, {type: "nonagon", sides: 9}, {type: "decagon", sides: 10}];
for (var i = 0; i < shapes.length; i++){
console.log(shapes[i].sides);
var sideExists = shapes.indexOf(shapes[i].sides) > -1;
if (sides === sideExists){
return shapes[i].type;
}else{
return 'Could not determine type';
}
}
};
我不認爲你可以用'indexOf'這樣。 – Redu