ES6箭头函数返回未定义而不是期望值 [英] ES6 arrow function returns undefined instead of desired value
本文介绍了ES6箭头函数返回未定义而不是期望值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在没有ES6的JS中运行的简单函数:
Easy function that works in JS without ES6:
var evenOrOdd = function(n){
if(n % 2 == 1){
return "Odd";
} else {
return "Even";
}
}
console.log(evenOrOdd(3)); //returns odd
我尝试使用ES6对其进行重组:
My attempt at restructuring this using ES6:
const evenOrOdd = (n) => {(n % 2 == 1) ? "Odd" : "Even"};
console.log(evenOrOdd(3)); //returns undefined
我在这里关注以下示例: 2ality 和 stoimen 。
I'm following these examples here: 2ality and stoimen.
此箭头函数为什么返回未定义
?
Why is this arrow function returning undefined
?
推荐答案
您必须删除 {}
。
const evenOrOdd = n => (n % 2 === 1 ? "odd" : "even")
console.log(evenOrOdd(3)) //=> "odd"
这篇关于ES6箭头函数返回未定义而不是期望值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文