ES6 Arrow Functions

In ES6, a new form of arrow function was added, which is actually a function;


Here's a brief look at :

< script >
let func = canshu => canshu;
console . log ( func ( 3 ));
</ script >


Above we defined a function in the form of an es6 arrow function;

let is equivalent to the previous var, used to define variables, but let has the nature of block-level scope;

func represents the function name;

The equal sign = is followed by our parameters;

After the arrow is our return value;


Compare and see :

< script >
//es6 way
let func = canshu => canshu;
console . log ( func ( 3 ));
// before our way
function func ( canshu ){
return (canshu);
}

//or write like this
var func = function( canshu){
return(canshu);
}
</ script>


上面的箭头函数默认的是一个参数的情况,如果我们有多个参数怎么写?

很简单,把参数用小括号括起来就可以了:

< script>
//es6的方式
let func =( canshu1, canshu2) => canshu1 +canshu2;
console. log( func( 3, 2));
</ script>



上面的函数的返回是只有一条语句时的情况,按上面的写法会默认返回,但是函数里面很少只有一个语句,

我们看看多条语句的情况下是如何来写?

< script>
//es6的方式
let func =( canshu1, canshu2) => {
if(canshu1 >canshu2){
return canshu1;
} else{
return canshu2;
}
};
console. log( func( 3, 8));
</ script>


首先多条语句,需要在箭头函数后面加上  { 语句都写在这里面 }

其次,返回值需要我们显式的写出来,也就是 return + 结果   ;


了解上面的部分就可以基本的使用箭头函数了,更多的详细信息请自行查阅文档;      

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324613522&siteId=291194637