&& 运算符未按预期工作

&& operator not working as intended

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

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

在你的行中看起来像:

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

根据您的要求,如果 x 或 y 为负数,您希望函数 return 未定义,我将按如下方式定义函数:

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