zoukankan      html  css  js  c++  java
  • [ES6] Converting an array-like object into an Array with Array.from()

    Array.from() lets you convert an "iterable" object (AKA an array-like object) to an array. In this lesson, we go over grabbing DOM nodes and turing them into an array so that we can use methods like Array.filter() and Array.forEach()on them.

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Array.from() example</title>
      </head>
      <body>
        <ul>
          <li class="product">15.99</li>
          <li class="product">7.99</li>
          <li class="product">32.99</li>
          <li class="product">24.99</li>
          <li class="product">5.99</li>
        </ul>
      </body>
      <script src="./index.js"></script>
    </html>
    const products =
      Array.from(document.querySelectorAll('.product'));
    
    products
      .filter(product => parseFloat(product.innerHTML) < 10)
      .forEach(product => product.style.color = 'red');

    What we got from document,querySelectorAll('.product') is 'NodeList', it is an array-like type, but cannot apply .filter, .map, .forEach to it. SO we use Array.from() method to convert is.

  • 相关阅读:
    深入Activity生命周期(一)
    android APK 中英文对比(转)
    android中获得系统语言
    mime Contenttype(http head)(转)
    activity设置全屏
    Activity常用知识
    关于这次数学建模
    排列组合
    hdu 1003 笔记
    杂想
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4987047.html
Copyright © 2011-2022 走看看