【问题标题】:What is the difference between these arrow functions [duplicate]这些箭头函数有什么区别[重复]
【发布时间】:2021-02-01 04:38:36
【问题描述】:
const post = text => (
   ....
)

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

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

【问题讨论】:

  • fn => 表达式,fn => 语句块

标签: javascript arrow-functions


【解决方案1】:
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 }

【讨论】:

    【解决方案2】:

    第一个箭头函数表示返回值(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"));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多