这些箭头功能之间有什么区别

时间:2020-10-18 04:36:59

标签: javascript arrow-functions

const post = text => (
   ....
)

const post = text => {
    ....
}

我是新来的,如果这是一个愚蠢的问题,对不起, 我搜索了一些文章,但没有得到。 有人可以帮忙解释

2 个答案:

答案 0 :(得分:4)

const post = text => (
   ....
)

此箭头函数需要用括号括起来的表达式或单个语句。调用函数时将返回表达式的结果。无需显式编写return

示例:

const isOdd = num => ( num % 2 == 1 );

第二个箭头函数需要一个函数体。如果您未明确返回,则将返回undefined

const post = text => {
    ....
}

示例:

const isOdd = num =>{
   return num % 2 == 1;
}

在第一种形式中,表达式并非总是需要(),但是在返回对象文字时是必需的。

const Point = (x,y) => {x,y};
console.log(Point(0,0)); //undefined
const Point = (x,y) => ({x,y});
console.log(Point(0,0)); //{ x: 1, y: 0 }

答案 1 :(得分:0)

第一个箭头功能表示返回值(what is return) 第二个箭头函数表示您要定义{define your function}的函数 有关更多说明,请遵循以下示例:

const post = text => (text) // return text

const post2 = text =>{ //define your function
  return (text)
}

console.log(post("hello post"));
console.log(post("hello post2"));

相关问题