Es2015 Array.from()的用法

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>




    <script>
        // 扩展运算符...
        let arr = [1,2,3];
        let arr2 = [...arr];
        arr.push(4);
        console.log(arr,arr2); // [1,2,3,4] [1,2,3]
        // Array.from()
        // 作用:把类数组(获取一组元素、arguments...)转换成数组
        // --------------------------------复制数组
        let arr3 = Array.from(arr);
        console.log(arr3);  // [1,2,3,4]
        window.onload = function (){
            let ali = document.querySelectorAll('ul li');
            console.log(ali);  // NodeList(5) [li, li, li, li, li]
            // ----------------------------把获取的元素转换成数组
            let arrli = Array.from(ali);
            // let arrli = [].slice.call(ali); //Es5之前的方法
            console.log(arrli); // (5) [li, li, li, li, li]
        };
        // ---------------------------------把arguments转换成数组
        function show(){
            // 正常的arguments是不能进行push操作的
            // console.log(arguments);  // Arguments(5) [1, 2, 3, 4, 5, callee: ƒ, Symbol(Symbol.iterator): ƒ]
            let args = Array.from(arguments);
            args.push(6);
            console.log(args);  // (6) [1, 2, 3, 4, 5, 6]
        };
        show(1,2,3,4,5);
        // ---------------------------------把字符串转换成数组
        // 传统方法
        let str = 'Hello';
        let strarr = str.split('');
        console.log(strarr);  // (5) ["H", "e", "l", "l", "o"]
        // Es6方法
        let strarr2 = Array.from(str);
        console.log(strarr2); // (5) ["H", "e", "l", "l", "o"]
        





    </script>
</body>
</html>
Last modification:June 12th, 2019 at 02:24 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment