我有这段代码:
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;
}
答案 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
给你:
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;
答案 2 :(得分:0)
如果我是你,我会使用高斯并以这种方式写下来:
function f(n)
{
return n > 0 && n % 2 === 0 ? n * (n + 1) / 2 : false;
}
console.log(f(4));
console.log(f(5));