何为伪数组?
伪数组有两个特征:1、按索引方式存储数据 ; 2、具有 length 属性。
简单地说就是长得像数组,然而并不是数组。比如函数中的 arguments、DOM中的 NodeList等。当然,还有一些可遍历的对象,看上去都像数组却不能直接使用数组的 API。
让伪数组可以使用数组的 API,传统的做法
基本原理就是使用 call 将数组的 API 应用到伪数组上面去
相当于利用函数的上下文来间接的使用数组的API
看例子
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
[].slice.call(arguments);
[].slice.call(document.querySelectorAll('img'));
ES6 提供了新的 API 来解决这类似的问题,Array.from
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
Array.from(arguments);
Array.from(document.querySelectorAll('img'));
Array.from()
不单单只有将伪数组转换为数组的功能,它还具有 map 的功能。
想要初始化一个长度为8的数组,数组的每个元素为10的时候,传统的做法
let arr = Array(9).join(' ').split('').map(item=>10)
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
这么写可以,但还不够简洁,如果使用 Array.from()
Array.from({ length: 8 }, function () { return 10 })
文章评论
您还未登录,无法评论文章,点击登录