2016-04-30 32 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>");