希望通过传入的边数(数字)来确定形状类型..下面的代码仅转到第一个索引,三 Angular 形..我的猜测是因为我没有正确地将边数与数组中的边属性进行比较?我尝试使用 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';
}
}
};
最佳答案
我可能更喜欢这样做。
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>");
关于javascript - 努力比较边数以确定形状类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36960354/