ES6练习

箭头函数、模板字符串(`${}`)、Promise、剩余参数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- <canvas id="canvas"></canvas> -->

    <script>
        // 处理对象属性:选出年龄大于80的人
        const people = [
            { name: "hh", age: 89 },
            { name: "uu", age: 88 },
            { name: "yy", age: 55 }
        ];
        const older = people.filter(person => person.age >= 80);
        console.log(older);

        // 处理数组:数组中每个元素乘以2
        const arr = [8, 9, 2, 5];
        const result = arr.map(x => x * 2);
        console.log(result);

        // 将数组中的元素打印出来
        arr.map(x => console.log(x));//map返回数组
        arr.forEach(x => console.log(x));//没有返回值 undefined
        let school = ['清华大学', '家里蹲', '黑龙江大学'];
        school.forEach(x => console.log(x));


        //array.push的用法:添加元素至数组末尾,返回新数组的长度
        let one = ['apple', 'orange'];
        let two = one.push('banana');
        console.log(one);//['apple', 'orange', 'banana']
        console.log(two);//3

        //使用箭头函数,将数组中的每个数×2,返回新数组
        const newArray = []
        newArray.push(arr.map(item => item * 2));
        console.log(newArray);

        //模板字符串 常量(包含换行和特殊字符而无需转义)
        const str = `just do 
        it!`
        console.log(str);//反引号
        //模板字符串 变量
        const hh = '嘿嘿';
        console.log(`我是${hh},你好`);//反引号
        //模板字符串 表达式
        const aa = 5, bb = 7;
        console.log(`${aa}+${bb}的result为${aa + bb}`);
        //模板字符串 函数
        function sayhii() {
            return 'hi yanyan!';
        }
        console.log(`你好!${sayhii()}`);

        // Promise:Promise 对象代表一个异步操作的最终完成(或失败)及其结果值。
        // Promises 有三种状态:pending(进行中)、fulfilled(已成功)和 rejected(已失败)
        // 当异步操作成功完成时,调用resolve来通知 Promise 的使用者操作成功了,并且可以传递一个结果值
        // 当异步操作出现错误或失败时,调用reject来通知 Promise 的使用者操作失败了,并且可以传递一个错误信息
        // .then方法接受一个回调函数作为参数。当 Promise 的状态变为 fulfilled 时,这个回调函数会被调用,并传入 Promise 成功时的结果值
        const myPromise = new Promise((resolve, reject) => {
            // Some asynchronous operation
            setTimeout(() => {
                resolve('Success!');
            }, 1000);
        });

        myPromise.then(result => {
            console.log(result); // 'Success!'
        });

        //剩余参数:允许将不确定数量的参数收集到一个数组中
        function sum(...numbers) {
            return numbers.reduce((total, num) => total + num, 0);//total=0;total=total+num;
        }
        console.log(sum(7, 9, 3)); // 6
        // console.log(typeof sum);

    </script>
</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值