您的位置:首页 > 移动开发 > Objective-C

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

2015-11-22 23:04 573 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: