html ES6 - Array.from()

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html ES6 - Array.from()相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Array .from()</title>
</head>
<body>
    <ul class="heroes">
        <li>Hulk</li>
        <li>Thor</li>
        <li>Iron Man</li>
        <li>Vision</li>
        <li>Misty Knight</li>
        <li>Jessica Jones</li>
        <li>The Punisher</li>
    </ul>
    <script>
    
        // Array.from takes in a function as a second argument, so you can directly return 
        // a value:
        const heroNodes = document.querySelectorAll('li');
        const heroes = Array.from(heroNodes, hero => hero.textContent);
        console.log(heroes);
        // Other ways to turn a nodelist into an array: 
        console.log(Array.prototype.slice.call(document.querySelectorAll('li')));
        // Using the ES6 spread operator
        console.log([...document.querySelectorAll('li')]);
        
        // Using Array.from to turn an arguments object into an array
        function sumAll() {
            const nums = Array.from(arguments);
            console.log(nums);
            return nums.reduce((a, b) => a + b);
        }

        sumAll(2, 34, 23, 234, 234, 234234, 234234, 2342);
    </script>
</body>
</html>

以上是关于html ES6 - Array.from()的主要内容,如果未能解决你的问题,请参考以下文章

es6数组去重(Set)

ES6之Array.from()方法

es6 Array.from() 将类似数组的对象转化为数组

ES6的Array.from()和Array.fill()方法

ES6,Array.from的用法

ES6的数组方法之Array.from