use*_*480 0 javascript ecmascript-6
我正在阅读本教程:React-Redux Basic
但我对Javascript中的箭头函数感到困惑.
我理解语法:
var myFunction = (para1, para2) => {statements}
Run Code Online (Sandbox Code Playgroud)
我可以使用: myFunction(para1, para2)
但我不明白语法:
var myFunction2 = ({para1, para2}) => (stattements)
Run Code Online (Sandbox Code Playgroud)
做什么({para1, para2})和(statements)意味着什么?
大家能帮帮我吗?对不起,我的英语不好.
你所说的是对象解构.
对象解构允许您同时从对象分配多个变量.例如:
let object = { foo: 3, bar: 7 };
// object destructuring
let { foo, bar } = object;
console.log(foo, bar); // prints "3 7"
Run Code Online (Sandbox Code Playgroud)
在函数参数中使用它时会发生同样的事情:
let myFunction = function({ foo, bar }) { // can use arrow functions or regular functions
console.log(foo, bar);
};
let object = { foo: 3, bar: 7 };
myFunction(object); // prints "3 7"
Run Code Online (Sandbox Code Playgroud)
此外,使用大括号和括号(或没有)之间的区别在于,只有大括号才能有多个语句,否则只能有一个表达式(将自动返回):
// these three are equivalent functions
let add1 = (x, y) => (x + y); // note the implicit return
let add2 = (x, y) => x + y; // we also don't need parentheses
let add3 = (x, y) => { return x + y; } // { ... } is just as a normal function body
Run Code Online (Sandbox Code Playgroud)
你可以在这里阅读更多相关信息.