打赏

JavaScript类数组转换为数组 面试题

1、JavaScript类数组转换为数组

(1)方法一:借用slice

(2)方法二:Array.from

 

2、代码

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

    <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>JavaScript类数组转换为数组</title>
    </head>

    <body>
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <script>
            //NodeList伪数组
            var div = document.getElementsByTagName('div')
            //方法一:借用slice方法
            function convertArray(obj) {
                return Array.prototype.slice.call(obj);
            }
            //方法二:使用ES6
            function convertArray2(obj) {
                return Array.from(obj);
            }
            console.log(convertArray(div));
            console.log(convertArray2(div));
        </script>
    </body>

</html>

 

posted @ 2018-03-26 10:16  孟繁贵  阅读(249)  评论(0编辑  收藏  举报
TOP