javascript Array.from()和Array.of()

Posted

tags:

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

//These are not on the array prototype. They are on the array itself.

//Array.of() 
// - just creates an array with however many arguments you pass it
Array.of(4, 'hello', {hello: 'hello', hi: 'hi'});
// [ 4, 'hello', { hello: 'hello', hi: 'hi' } ]

//Array.from()
// - Very useful when working with DOM elements
// - first param is the DOM node. For example. document.querySelectorAll('.people p');
// - also takes in a second parameter, a map function
// - allows you to modify the data as you create the array

`
<div class="people">
    <p>Wes</p>
    <p>Kait</p>
    <p>Snickers</p>
</div>
`

const people = document.querySelectorAll('.people p');

const peopleArray = Array.from(people, person => {
  console.log(person);
  return person.textContent;
});

console.log(peopleArray);

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

转 JavaScript里的数组转化新方法Array.From

javascript Array.from polyfill(另请参阅https://github.com/mathiasbynens/Array.from)

javascript Array.from()

javascript 中Array一些高效的操作方法

javascript学习系列(19):数组中的Array.from方法

javascript的数组之from()