简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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