Array.from()
和 Array.of()
這兩個(gè)函數(shù)的操作對(duì)于我們一些常見(jiàn)的操作和流程判斷是非常方便有用的。他們并不是原型上的方法
Array.from()
用于把類數(shù)組對(duì)象,或一個(gè)可遍歷對(duì)象轉(zhuǎn)換為一個(gè)真正的數(shù)組
類數(shù)組對(duì)象就是擁有 length
屬性的對(duì)象
可遍歷對(duì)象就是部署了可遍歷接口 iterable
的對(duì)象
// 擁有 `length` 屬性的nodelist對(duì)象
const todos = document.querySelectorAll('li');
const todosArr = Array.from(todos); // 將類數(shù)組對(duì)象轉(zhuǎn)換為真是數(shù)組
const names = todosArr.map(todo=>todo.textContent);
console.log(name);
// 以上可以簡(jiǎn)寫(xiě)為,轉(zhuǎn)換為數(shù)組后相當(dāng)于調(diào)用了 `map` 方法
const name = Array.from(todos, todo => todo.textContent);
// 擁有 `length` 屬性的arguments對(duì)象
function sum() {
return Array.from(arguments).reduce((prev, curr) => prev + curr, 0);
}
// 字符串
const str = 'laravel';
console.log(Array.from(str));
Array.of()
返回有參數(shù)組成的數(shù)組
new Array(3)
是創(chuàng)建一個(gè)長(zhǎng)度為3的數(shù)組,而不是元素為3的數(shù)組
Array.of()
返回結(jié)果一致性,Array.of(3)
創(chuàng)建的就是一個(gè)元素為3的數(shù)組