我们可以在条件运算符(?:)中运行循环吗?

时间:2017-06-12 05:59:55

标签: javascript conditional ternary

我有这段代码:

function f(n){
var p = 0;
if(n % 2 === 0 && n > 0) {
  for(let i = 1; i <= n; i++) {
    p += i;
  };
} else {
    return false;
    }
 return p;
};

并且想知道是否有可能转换为三元运算符来缩短它。这是我提出的代码,但它显然不正确,任何见解都会很好!欢呼声。

function f(n){
  var p = 0;
  ((n % 2 === 0) && (n > 0)) ? for(let i = 1; i <= n; i++) {p += i;} : 
  false;
  return p;
}

3 个答案:

答案 0 :(得分:0)

您只能在conditional (ternary) operator ?:内使用表达式。 for语句不是表达式。

但你可以使用三元语句,没有for循环和高斯公式来获取偶数的结果。

function f(n) {
    return n % 2 === 0 && n > 0 ? n * (n + 1) / 2 : false;
}

console.log(f(4));
console.log(f(5));

更短的版本可以使用logical AND &&

function f(n) {
    return n % 2 === 0 && n > 0 && n * (n + 1) / 2;
}

console.log(f(4));
console.log(f(5));

另一个可能性是将整个for语句包装在IIFE中。

function f(n){
    return n % 2 === 0 && n > 0 ? function (p) {
        for (let i = 1; i <= n; i++) {
            p += i;
        }
        return p;
    }(0) : false;
}

console.log(f(4));
console.log(f(5));

答案 1 :(得分:0)

你不能在三元内部使用if,
Insted你可以使用一个函数来for给你:

&#13;
&#13;
function calc(num){
  var p = 0;
   for(let i = 1; i <= num; i++) {
     p += i;
   }
   
   return p;
}

function f(n){
  var p = 0;
  p = ((n % 2 === 0) && (n > 0)) ? calc(n) : 
  false;
  return p;
}

console.log(f(4));
console.log(f(5));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果我是你,我会使用高斯并以这种方式写下来:

function f(n)
{
  return n > 0 && n % 2 === 0 ? n * (n + 1) / 2 : false;
}

console.log(f(4));
console.log(f(5));