简体   繁体   English

努力比较边数以确定形状类型

[英]Struggling to compare number of sides to determine shape type

Looking to determine shape type by sides (number) passed in .. code below only goes to first index, triangle .. my guess is because I'm not properly comparing sides number to sides property in array?希望通过传入的边(数字)确定形状类型.. 下面的代码只转到第一个索引,三角形.. 我的猜测是因为我没有正确比较边数和数组中的边属性? I tried using filter , forEach , and map and ran into rabbit hole.我尝试使用filterforEachmap并遇到了兔子洞。 Thanks in advance for the help.在此先感谢您的帮助。

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

I would probably prefer doing like this.我可能更喜欢这样做。

 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>");

The loop seems to need to compare the sides parameter to the sides in the shapes array, something more like this:循环似乎需要将边参数与形状数组中的边进行比较,更像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM