繁体   English   中英

如何使用没有花括号的 if 来编写较短的箭头 function

[英]How do I write a shorter arrow function using an if without curly braces around the body

我想要这个,但使用箭头的行数更少

 console.log([1, 2, 3, 4].every( value => { if (value > 0) { return 1 } }))

output:真

它工作正常但是当我试图减少下面的代码行时它不起作用有没有办法做到这一点,是否可以在不使用任何三元的情况下编写单个 if 语句

console.log([1, 2, 3, 4].every(value =>
  if (value > 0) 1)
);
output :  /tmp/main.js:1
console.log([1,2,3,4].every(value=> if(value>0) 1)) 
                                    ^^

SyntaxError: Unexpected token 'if'
    at Module._compile (internal/modules/cjs/loader.js:892:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at internal/main/run_main_module.js:17:11

[Program exited with exit code 1]

是否可以使用像这样的箭头运算符返回除 true 或 false 之外的任何内容? 我想返回真棒,但它给我一个错误。

k=val=>val>0 "awesome";
console.log(k(2))
k=val=>val>0 "awesome";
             ^^^^^^^^^

SyntaxError: Unexpected string
    at Module._compile (internal/modules/cjs/loader.js:892:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at internal/main/run_main_module.js:17:11

我试图问这个基于箭头 function 的问题,但有人告诉我单独问这个问题,这就是我在这里问的原因。

您可以通过以下方式进行

 console.log([1, 2, 3, 4].every(value => value > 0))

 console.log([1, 2, 3, 4].every(value => value > 0)? "awesome": null)

是的,您可以在箭头函数中使用 if 语句。

例子

 function wait() { return new Promise((resolve) => { setTimeout(() => resolve(1), 5000); }); } async function main() { wait().then((a) => { if (a == 1) console.log(`Yes`); else console.log(`Nope`) }) } main();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM