这些箭头函数有什么区别
What is the difference between these arrow functions
const post = text => (
....
)
和
const post = text => {
....
}
我是新手,抱歉,如果这是一个愚蠢的问题,
我已经搜索了一些文章,但没有得到它。
谁能帮忙解释一下
第一个箭头函数表示return一个值(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"));
const post = text => (
....
)
此箭头函数需要括号中的表达式或单个语句。当您调用该函数时,表达式的结果将被 returned。无需显式写 return
。
示例:
const isOdd = num => ( num % 2 == 1 );
第二个箭头函数需要一个函数体。如果您没有明确 return,undefined
将被 returned。
const post = text => {
....
}
示例:
const isOdd = num =>{
return num % 2 == 1;
}
在第一种形式中,您并不总是需要 ()
围绕表达式,但是当您 return 一个对象文字时,它是必需的。
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 }
const post = text => (
....
)
和
const post = text => {
....
}
我是新手,抱歉,如果这是一个愚蠢的问题, 我已经搜索了一些文章,但没有得到它。 谁能帮忙解释一下
第一个箭头函数表示return一个值(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"));
const post = text => (
....
)
此箭头函数需要括号中的表达式或单个语句。当您调用该函数时,表达式的结果将被 returned。无需显式写 return
。
示例:
const isOdd = num => ( num % 2 == 1 );
第二个箭头函数需要一个函数体。如果您没有明确 return,undefined
将被 returned。
const post = text => {
....
}
示例:
const isOdd = num =>{
return num % 2 == 1;
}
在第一种形式中,您并不总是需要 ()
围绕表达式,但是当您 return 一个对象文字时,它是必需的。
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 }