-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# `Array.from()` 和 `Array.of()` | ||
> 这两个函数的操作对于我们一些常见的操作和流程判断是非常方便有用的。他们并不是原型上的方法 | ||
### `Array.from()`用于把类数组对象,或一个可遍历对象转换为一个真正的数组 | ||
|
||
类数组对象就是拥有 `length` 属性的对象 | ||
可遍历对象就是部署了可遍历接口 `iterable` 的对象 | ||
``` | ||
// 拥有 `length` 属性的nodelist对象 | ||
const todos = document.querySelectorAll('li'); | ||
const todosArr = Array.from(todos); // 将类数组对象转换为真是数组 | ||
const names = todosArr.map(todo=>todo.textContent); | ||
console.log(name); | ||
// 以上可以简写为,转换为数组后相当于调用了 `map` 方法 | ||
const name = Array.from(todos, todo => todo.textContent); | ||
// 拥有 `length` 属性的arguments对象 | ||
function sum() { | ||
return Array.from(arguments).reduce((prev, curr) => prev + curr, 0); | ||
} | ||
// 字符串 | ||
const str = 'laravel'; | ||
console.log(Array.from(str)); | ||
``` | ||
|
||
### `Array.of()`返回有参数组成的数组 | ||
`new Array(3)` 是创建一个长度为3的数组,而不是元素为3的数组 | ||
`Array.of()` 返回结果一致性,`Array.of(3)` 创建的就是一个元素为3的数组 |