【发布时间】:2021-02-01 04:38:36
【问题描述】:
const post = text => (
....
)
和
const post = text => {
....
}
我是新人,如果这是一个愚蠢的问题,对不起, 我搜索了一些文章,但没有得到它。 谁能帮忙解释一下
【问题讨论】:
-
fn => 表达式,fn => 语句块
标签: javascript arrow-functions
const post = text => (
....
)
和
const post = text => {
....
}
我是新人,如果这是一个愚蠢的问题,对不起, 我搜索了一些文章,但没有得到它。 谁能帮忙解释一下
【问题讨论】:
标签: javascript arrow-functions
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 }
【讨论】:
第一个箭头函数表示返回值(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"));
【讨论】: