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

标签 javascript arrays for-loop

希望通过传入的边数(数字)来确定形状类型..下面的代码仅转到第一个索引,三 Angular 形..我的猜测是因为我没有正确地将边数与数组中的边属性进行比较?我尝试使用 filterforEachmap 并遇到了兔子洞。先谢谢您的帮助。

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/

相关文章:

javascript 匿名函数的变量作用域

javascript - 如何将不同的位置放在随机添加的图像上? Vue.js

bash - 使用 tr 删除多个文件中的换行符?

javascript - 在客户端以 html 的形式在 javascript 中显示 Git diff

javascript - 自动滚动 AngularJS 似乎不起作用

java - 我不明白为什么它说 ArrayOutOfBound 错误

c - 即使两个变量包含相同的字符串,sizeof() 也返回不同的值

linux - 在管道 awk 输出上打印循环输入文件名

Javascript:循环访问多个对象的相同属性

javascript - 无法让defaultsTo与waterline/sailsjs一起使用