Array.from可通过1、类数组(arguments)2、可迭代对象(set,map)来创建新数组。
1 | // 后面两个参数可选 |
- arrayLike: 必选,1、类数组(argumentg)2、可迭代对象(set,map)。
- mapFn: 可选,相当于Array.from(arrayLike).map(mapFn, thisArg)。
- thisArg: 可选,执行回调函数mapFn时候的this对象。非常有用,利于解耦。可以把被处理的数据和对象分离,thisArg中定义处理函数handle,用来在mapFn中返回调用handle之后的结果。
用法
string
1 | const a = Array.from('abc'); |
new Set()
1 | const b = Array.from(new Set([1,2,3])); |
new Map()
1 | const c = Array.from(new Map([[1, 2], [3, 4]])); |
类数组
1 | const d = (function() { |
使用第二个参数func返回新函数
1 | const e = Array.from([1,2,3], x => x*2); |
1 | const f = Array.from({length: 5}, (v, i) => i + 1); |
数组去重合并
1 | const g1 = [1,2,3,4]; |
充分利用第三个参数thisArg
1 | const obj = { |
思路
判断如果第一个参数arrayLike为空,throw new TypeError(“Array.from requires an array-like object - not null or undefined”);
循环arrayLike,判断如果有第二个参数mapFn,则返回arr[i] = mapFn(arrayLike[i], i); 否则直接返回arrayLike[i]
判断如果有第三个参数,mapFn调用的时候mapFn.apply(this, arrayLike[i], i)
返回arr
ps: polyfill的代码和底层实现的未必是完全一致的。比如这里使用new Set[1,2,3]和new Map[[a,1],[b,1]]返回的值都是[]。因为能支持es6代码的浏览器基本都不需要polyfill实现Array.from。
代码实现
1 | Array.from = (function() { |
测试代码
1 | const Array = require('./index'); |