Javascript:3个计算三角形,圆形或矩形的面积的函数返回未定义

时间:2018-08-21 09:35:34

标签: javascript function if-statement

很抱歉,这个非常简单的问题,但是我似乎无法缩小为什么以下函数对所有结果都返回“ undefined”的原因。这是我的代码:

function calculateTriangleArea(x, y){
  x * y / 2 
}
function calculateRectangleArea(x, y){
  x * y
}
function calculateCircleArea(x){
  Math.PI * x * x
}

if (calculateRectangleArea.name === true)
 (function calculateRectangleArea(x, y)
  {return [x * y]
})
if (calculateTriangleArea.name === true)
  (function calculateTriangleArea(x, y){
   return[x * y / 2]
})

else (function calculateCircleArea(x){
  return [Math.PI * x * x]
})

当我运行这9个console.log命令时,它们都将返回未定义状态。

console.log(calculateRectangleArea(10, 5));     // should print 50
console.log(calculateRectangleArea(1.5, 2.5));  // should print 3.75
console.log(calculateRectangleArea(10, -5));    // should print undefined
console.log(calculateTriangleArea(10, 5)); // should print 25
console.log(calculateTriangleArea(3, 2.5)); // should print 3.75
console.log(calculateTriangleArea(10, -5)); // should print undefined
console.log(calculateCircleArea(10)); // should print 314.159...
console.log(calculateCircleArea(3.5)); // should print 38.484...
console.log(calculateCircleArea(-1)); // should print undefined

2 个答案:

答案 0 :(得分:2)

您在returncalculateTriangleAreacalculateRectangleArea上缺少calculateCircleArea。由于它们在其他函数内部使用,因此您也需要从这些函数返回值:

function calculateTriangleArea(x, y) {
  return x * y / 2
}

function calculateRectangleArea(x, y) {
  return x * y
}

function calculateCircleArea(x) {
  return Math.PI * x * x
}

if (calculateRectangleArea.name === true)
  (function calculateRectangleArea(x, y) {
    return [x * y]
  })
if (calculateTriangleArea.name === true)
  (function calculateTriangleArea(x, y) {
    return [x * y / 2]
  })

else(function calculateCircleArea(x) {
  return [Math.PI * x * x]
})

console.log(calculateRectangleArea(10, 5));
console.log(calculateRectangleArea(1.5, 2.5));
console.log(calculateRectangleArea(10, -5));
console.log(calculateTriangleArea(10, 5));
console.log(calculateTriangleArea(3, 2.5));
console.log(calculateTriangleArea(10, -5));
console.log(calculateCircleArea(10));
console.log(calculateCircleArea(3.5));
console.log(calculateCircleArea(-1));

答案 1 :(得分:0)

您需要返回值,可以使用ES6语法。

const calculateTriangleArea = (x, y) => x * y / 2 ;