三元运算符 returns 'undefined' 而不是期望值

Ternary operator returns 'undefined' instead of expected value

给定一个数字,该函数必须 return 该数字的负数(它可能已经是负数)。为什么三元运算符在这种情况下不起作用?使用 if 语句有效。

// Does not work
function makeNegative(num) {
  num < 0 ? num : -num;
}

// Works
function makeNegative(num) {
  if (num < 0) {
    return num;
  }
  return -num;
}

// TEST
console.log(makeNegative(-4)); //-4
console.log(makeNegative(6)); //-6

您还需要return您的价值:

function makeNegative(num) {
    return num < 0 ? num : -num;
}

如果你想使用隐式returns,你需要将你的函数转换为箭头函数:

const makeNegative = num => num < 0 ? num : -num;

顺便说一句,您可以为此目的使用否定 Math.abs()

const alwaysNegative = -Math.abs(num);

您需要分配 num,您缺少 =:

function makeNegative(num) {
  num = (num < 0) ? num : -num;
}

更多信息,您可以查看docs

编辑:我又看了一遍这个问题,考虑到在这种情况下的用法,这是行不通的。如果您希望将该方法应用于没有 return 值的数字,这就是解决方案,但在这种情况下,您需要寻找 return 语句。我会把我的答案留在这里作为其他人的参考,但这不是@Awscr 问题的答案。

您在三元运算符函数中缺少 return 语句。像这样尝试:

function makeNegative(num) {
  return(num < 0 ? num : -num);
}