4_箭头函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //原本的函数
        function demo_1(a,b){
            return a+b;
        }
        console.log(demo_1(1,2));
        //简化为箭头函数
        demo_2=(a,b)=>{
            return a+b;
        }
        console.log(demo_2(1,2));
        //如果箭头函数只有一句返回值,还可以简写为
        demo_3=(a,b)=>a+b;
        console.log(demo_3(1,2));


        //利用箭头函数实现map和reduce
        let arr = [1,2,3,4];
        var map = arr.map((currentValue)=>{
            return currentValue*2;
        });
        var reduce = arr.reduce((accumulator, currentValue) => {
            return accumulator+currentValue;
        });
        console.log("map函数后得到的数组");
        console.log(map);
        console.log("reduce函数后得到的数组");
        console.log(reduce);
    </script>
</body>
</html>
箭头函数是 ES6 引入的一种新的数定义方式,使用 `=>` 符号定义,具有语法简洁、词法 `this` 绑定和隐式返回等特点,在回调数、事件处理、立即执行数和对象方法等场景中非常有用,能帮助开发者编写更简洁、更可靠的代码[^1]。 ### 基本语法 箭头函数的基本语法根据参数数量和数体的不同而有所变化: - **多参数,有数体**:`const func = (参数) => { 数体 };` - **单参数,有数体**:单参数可省略括号,如 `const square = x => { return x * x; };` - **单参数,隐式返回**:可省略 `return` 和大括号,如 `const square = x => x * x;` - **无参数**:需要空括号,如 `const sayHello = () => "Hello World";` - **多参数,隐式返回**:多参数必须使用括号,如 `const add = (a, b) => a + b;` [^2] ### 特点 1. **语法简洁**:相较于传统数,箭头函数的语法更加简洁,减少了代码量。例如传统数 `function add(a, b) { return a + b; }`,使用箭头函数可以写成 `const add = (a, b) => a + b;` [^1][^2][^3] 2. **词法 `this` 绑定**:箭头函数没有自己的 `this`,它的 `this` 值继承自外层数,这避免了传统数中 `this` 指向问题带来的困扰。 3. **隐式返回**:当箭头函数数体只有一条语句时,可以省略 `return` 关键字,该语句的执行结果会自动作为返回值。例如 `const square = x => x * x;` 会自动返回 `x * x` 的结果 [^1][^2] 4. **参数获取**:可以在参数内以 `...args` 的方式获取输入的参数,得到的 `args` 是一个数组。例如: ```javascript const func = (...args) => { console.log(args); // [ 1, 2, 3 ] }; func(1, 2, 3); ``` [^4] ### 注意事项 1. **不能作为构造数**:箭头函数不能使用 `new` 关键字来创建对象,因为它没有自己的 `this` 和 `prototype` [^5] 2. **不能用于需要动态 `this` 的对象方法**:由于箭头函数的 `this` 是词法绑定的,在需要动态 `this` 的场景中不适用 [^1][^5] 3. **没有 `arguments` 对象**:箭头函数没有自己的 `arguments` 对象,如果需要获取参数,可以使用剩余参数语法 `...args` [^4][^5] 4. **不支持 `yield`**:不能用作 Generator 数 [^5] ### 示例代码 ```javascript // 基本示例 const multiply = (a, b) => a * b; console.log(multiply(3, 4)); // 输出: 12 // 使用剩余参数 const sumAll = (...numbers) => { return numbers.reduce((total, num) => total + num, 0); }; console.log(sumAll(1, 2, 3, 4)); // 输出: 10 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值