不确定使用&&运算符的错误是什么,但是输出不正确。这是我的代码:
function calculateTriangleArea(x, y) {
return x * y / 2
}
function calculateRectangleArea(x, y) {
return x * y
}
function calculateCircleArea(x) {
return Math.PI * x * x
}
if (function calculateRectangleArea(x, y) {
calculateRectangleArea.name === true &&
x > 0 && y > 0
})
(function calculateRectangleArea(x, y) {
return [x * y]
})
else if (function calculateTriangleArea(x, y) {
calculateTriangleArea.name === true &&
(x > 0 && y > 0)
})
(function calculateTriangleArea(x, y) {
return [x * y / 2]
})
else if (function calculateCircleArea(x, y) {
calculateCircleArea.name === true &&
x > 0
})
(function calculateCircleArea(x, y) {
return [Math.PI * x * x]
})
else {
return undefined
}
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
如果变量X或Y为负整数,我试图使函数返回未定义的值。现在,它只是输出整数。
答案 0 :(得分:1)
根据您的要求,如果x或y为负,则希望函数返回未定义的值,我将对函数进行如下定义:
function calculateTriangleArea(x, y) {
if (x < 0 || y < 0) { //Check if x is < 0 or y is < 0
return undefined; //Return undefined if that is true.
}
return x * y / 2; //Else calculate the output and return it
}
function calculateRectangleArea(x, y) {
if (x < 0 || y < 0) {
return undefined;
}
return x * y;
}
function calculateCircleArea(x) {
if (x < 0) {
return undefined;
}
return Math.PI * x * x;
}
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
答案 1 :(得分:-1)
您的行看起来像:
if (function calculateRectangleArea(x, y){
您正在声明一个函数。
举个例子,这就是你正在做的:
function foo(x) {
return x%2 ===0; // x is an even number;
}
if (function foo(2)) {
console.log("we got here");
}
我刚遇到语法错误。
如果您删除function
关键字,则您的代码可能会更好地工作,例如:
if (calculateRectangleArea(x, y){