// js 原生方式声明函数
function say(name){ console.log("hello" + name); }
// 箭头函数
var say = name => console.log("hello " + name); // hello tom
say("tom");
// 多个参数
function sum1(a, b) { return a + b; } var sum2 = (a, b) => a + b; console.log(sum1(2, 3)); // 5 console.log(sum2(2, 3)); // 5
// 复杂函数声明
var MAX = (a, b) => { if (a > b) { return a; } else { return b; } }
// 箭头函数+解构表达式
person = { name: 'jerry', age: 12, language: ['java', 'python', 'go'] } var hello = (person) => { console.log("hello "+person.name); // hello jerry } // 用结构表达式 var hi = ({name}) => { console.log("hi " + name); // hi jerry } hello(person) hi(person)
求数组平均值
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length; // arrayAverage([1,2,3]) -> 2