寻找确定形状类型的边(数)传入..下面的代码只去第一个索引,三角形..我的猜测是因为我没有正确比较边数数组中的属性?我试着用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