2016-04-30 31 views
1

尋找確定形狀類型的邊(數)傳入..下面的代碼只去第一個索引,三角形..我的猜測是因爲我沒有正確比較邊數數組中的屬性?我試着用filter,forEachmap跑進兔子洞。先謝謝您的幫助。努力比較邊數量來確定形狀類型

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'; 
    } 
    } 
}; 
+0

我不認爲你可以用'indexOf'這樣。 – Redu

回答

0

循環似乎需要雙方參數形狀數組中比較的四周,更多的東西是這樣的:

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++){ 

    if (sides === shapes[i].sides){ 
     return shapes[i].type; 
    } 
    } 

    return 'Could not determine type'; 
}; 
+0

謝謝@fordareh它的工作原理,我只是在'this.sides'這個陳述中做'雙方'..再次感謝 – gmatsushima

1

我可能會更喜歡做這樣的。

var Shape = function(sides) { 
 
    (sides < 3 || typeof sides !== 'number') ? this.sides = 0 : this.sides = Math.floor(sides); 
 
}; 
 

 
Shape.prototype.getType = function(){ 
 
    var shapes = {0: "not defined shape", 3: "triangle", 4: "quadrilateral", 5: "pentagon", 6: "hexagon", 7: "heptagon", 8: "octagon", 9: "nonagon", 10: "decagon"}; 
 
    return shapes[this.sides]; 
 
} 
 

 
var square = new Shape(7); 
 
document.write("<pre> I am a " + square.getType() + "</pre>");