箭头函数就是匿名函数,它是一种更加精简的的格式
箭头函数的参数
1、如果一个函数没有参数,使用()
2、如果只有一个参数,参数列表可以省略小括号()
3、多个参数不能省略小括号(),
箭头函数的返回值
1、如果函数体部分有多行,就需要使用{},如果有返回值使用 return
2、如果只有一行语句,可以同时省略大括号和 return
3、只要有 return 语句,就不能省略大括号;有 return 就必须有大括号
4、如果中有一条非 return 语句,加上大括号,函数就成了无返回值了
console.log(((x, y, z) => x*2 + y + z)(2, 4, 6))
console.log(((x) => x*2 + x + x)(2))
console.log((() => {console.log('log abc');return 'return abc';})())
console.log((() => {console.log('No Return')})()) // No return
Info: Start process (下午7:57:32)
14
8
log abc
return abc
No Return
undefined
Info: End process (下午7:57:32)
const map = function (arr, fn) {
let newarr = []
for (let i in arr) {
newarr[i] = fn(arr[i])
}
return newarr
}
console.log("=".repeat(25))
console.log(10, map([1, 2, 3, 4, 5], (x) => {return x++}))
console.log("=".repeat(25))
console.log(20, map([1, 2, 3, 4, 5], x => {return ++x}))
console.log("=".repeat(25))
console.log(30, map([1, 2, 3, 4, 5], x => x+1))
console.log("=".repeat(25))
console.log(40, map([1, 2, 3, 4, 5], function(x) {return x+=1}))
console.log("=".repeat(25))
console.log(50, map([1, 2, 3, 4, 5], x => console.log(x)))
console.log("=".repeat(25))
console.log(60, map([1, 2, 3, 4, 5], y => {y}))
console.log("=".repeat(25))
Info: Start process (下午4:02:04)
=========================
10 [ 1, 2, 3, 4, 5 ]
=========================
20 [ 2, 3, 4, 5, 6 ]
=========================
30 [ 2, 3, 4, 5, 6 ]
=========================
40 [ 2, 3, 4, 5, 6 ]
=========================
1
2
3
4
5
50 [ undefined, undefined, undefined, undefined, undefined ]
=========================
60 [ undefined, undefined, undefined, undefined, undefined ]
=========================
Info: End process (下午4:02:04)