首页 > 解决方案 > 关于给定负数将函数返回为“未定义”的问题?

问题描述

我正在尝试编写undefined如果给定负数将返回的代码

我被要求使用 Javascript 中的函数计算矩形、三角形和圆形的面积。我说对了那部分,但问题还说“如果任何参数为负,则函数应返回未定义。

function calculateRectangleArea (length, width) {
  return length * width;
}
function calculateTriangleArea (base, height) {
  return (base * height)/2;
}
function calculateCircleArea (radius) {
  return radius * radius * Math.PI;
}

我可以很好地计算面积,但如果要得到一个负数,我不知道该写什么undefined。是不是像:

if (calculateRectangleArea <0) 
   return "undefined";

标签: javascriptfunctionecmascript-6

解决方案


您需要在语句中测试每个参数以确保它不是负数,if如果有负数,则返回undefined- 否则,像您已经在做的那样返回普通计算:

function calculateRectangleArea(length, width) {
  if (length < 0 || width < 0) {
    return undefined;
  } else {
    return length * width;
  }
}
function calculateTriangleArea(base, height) {
  if (base < 0 || height < 0) {
    return undefined;
  } else {
    return (base * height) / 2;
  }
}
function calculateCircleArea(radius) {
  if (radius < 0) {
    return undefined;
  } else {
    return radius * radius * Math.PI;
  }
}

或者,由于没有返回值时,undefined默认返回,如果所有参数都是非负的,您也可以只返回计算,例如:

function calculateRectangleArea(length, width) {
  if (length >= 0 && width >= 0) {
    return length * width;
  }
}

推荐阅读