首页 > 其他 > 详细

[ES6] Converting an array-like object into an Array with Array.from()

时间:2015-11-23 00:43:13      阅读:257      评论:0      收藏:0      [点我收藏+]

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.

[ES6] Converting an array-like object into an Array with Array.from()

原文:http://www.cnblogs.com/Answer1215/p/4987047.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!