[英]How do I write a shorter arrow function using an if without curly braces around the body
I want this but in fewer lines using arrows我想要这个,但使用箭头的行数更少
console.log([1, 2, 3, 4].every( value => { if (value > 0) { return 1 } }))
output: true
output:真
It is working fine but when I tried to reduce the lines as below code it is not working is there any way to do it, is it not possible to write a single if statement without using any ternary它工作正常但是当我试图减少下面的代码行时它不起作用有没有办法做到这一点,是否可以在不使用任何三元的情况下编写单个 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]
Is it possible to return anything apart from true or false using arrow operator like this?是否可以使用像这样的箭头运算符返回除 true 或 false 之外的任何内容? I want to return awesome but it is throwing me an error.
我想返回真棒,但它给我一个错误。
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
I tried to ask this question which is based on arrow function but someone told me to ask the question separately, that's why I'm asking here.我试图问这个基于箭头 function 的问题,但有人告诉我单独问这个问题,这就是我在这里问的原因。
You can do it in the following way您可以通过以下方式进行
console.log([1, 2, 3, 4].every(value => value > 0))
console.log([1, 2, 3, 4].every(value => value > 0)? "awesome": null)
Yes, you can use if statements inside arrow functions.是的,您可以在箭头函数中使用 if 语句。
Example例子
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.