我们可以在条件运算符 (? :) 中 运行 for 循环吗?
Can we run for loops inside a conditional operator (? :)?
我有这个代码:
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;
}
您只能在 conditional (ternary) operator ?:
. A 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));
你不能在三元内部使用 for,
相反,你可以使用一个函数来为你做 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));
如果我是你,我会使用高斯并这样写:
function f(n)
{
return n > 0 && n % 2 === 0 ? n * (n + 1) / 2 : false;
}
console.log(f(4));
console.log(f(5));
我有这个代码:
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;
}
您只能在 conditional (ternary) operator ?:
. A 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));
你不能在三元内部使用 for,
相反,你可以使用一个函数来为你做 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));
如果我是你,我会使用高斯并这样写:
function f(n)
{
return n > 0 && n % 2 === 0 ? n * (n + 1) / 2 : false;
}
console.log(f(4));
console.log(f(5));