javascript - 关于给定负数将函数返回为“未定义”的问题?
问题描述
我正在尝试编写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";
解决方案
您需要在语句中测试每个参数以确保它不是负数,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;
}
}
推荐阅读
- amazon-web-services - 使用 moto 进行基本的 AWS Glacier 模拟失败
- kubernetes - 如何在 Kubernetes(仅生产者端事务)设置中选择 Kafka transactional.id
- javascript - :target 什么时候计算?
- python - Plotly Python:如何在零上隐藏网格刻度?
- android - Android - 文本的图像右侧与屏幕水平重叠
- salesforce - Salesforce中的数组查询
- ocaml - OCaml - 为什么不是 Monad
- mobile - 与 Testproject、TestSigma 等 AI 自动化工具相比,使用 Appium 有什么优势?
- java - SpringBootTest 每次运行前如何设置环境变量?
- angular - 从 npm 安装的库中访问 Angular 项目级文件