ES6基础知识(数组from方法)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>数组from方法</title>
</head>
<body>
    <script>
        /*Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。*/
        // let arrayLike = {
        //     '0': 'a',
        //     '1': 'b',
        //     '2': 'c',
        //     length: 3
        // };

        // // ES5的写法
        // var arr1 = [].slice.call(arrayLike);
        // console.log(arr1); // ['a', 'b', 'c']

        // // ES6的写法
        // let arr2 = Array.from(arrayLike);
        // console.log(arr2); // ['a', 'b', 'c']

        // NodeList对象
        // let ps = document.querySelectorAll('p');
        // Array.from(ps).filter(p => {
        //     return p.textContent.length > 100;
        // });

        // arguments对象
        // function foo() {
        //     var args = Array.from(arguments);
        //     console.log(args);//(3) [1, 2, 3]
        // }
        // foo(1,2,3);

        /*值得提醒的是,扩展运算符(...)也可以将某些数据结构转为数组。*/
        // arguments对象
        // function foo() {
        // const args = [...arguments];
        // }

        // // NodeList对象
        // [...document.querySelectorAll('div')]        

        //Iterator 接口的数据结构
        // console.log(Array.from('hello'));// ['h', 'e', 'l', 'l', 'o']

        // let namesSet = new Set(['a', 'b'])
        // console.log(Array.from(namesSet)) // ['a', 'b']                

        /*因此,任何有length属性的对象,都可以通过Array.from方法转为数组*/
        // console.log(Array.from({ length: 3 }));// [ undefined, undefined, undefined ]

        /*Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。*/
        // Array.from(arrayLike, x => x * x);
        // // 等同于
        // Array.from(arrayLike).map(x => x * x);
        // console.log(Array.from([1, 2, 3], (x) => x * x));// [1, 4, 9]        

    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/xingxingclassroom/p/10399418.html