&&&运算符未按预期工作



不确定我在使用 && 运算符时犯了什么错误,但输出不正确。这是我的代码:

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 是负整数,我正在尝试让我的函数返回未定义。现在它只是输出整数。

按照您的要求,如果 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

在你的行中,看起来像:

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){

相关内容

  • 没有找到相关文章

最新更新