Array.from() 方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
console.log(Array.from('foo')) // ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x)) // [2, 4, 6]
Array.from() 可以通过以下方式来创建数组对象:
- 伪数组对象(拥有一个 length 属性和若干索引属性的任意对象)
- 可迭代对象(可以获取对象中的元素,如 Map和 Set 等) Array.from() 方法有一个可选参数 mapFn,让你可以在最后生成的数组上再执行一次 map 方法后再返回。也就是说 Array.from(obj, mapFn, thisArg) 就相当于 Array.from(obj).map(mapFn, thisArg), 除非创建的不是可用的中间数组。 这对一些数组的子类,如 typed arrays 来说很重要, 因为中间数组的值在调用 map() 时需要是适当的类型。
from() 的 length 属性为 1 ,即 Array.from.length === 1。
利用Array.from()实现数组去重合并
function combineUnquie() {
const args = [].concat.apply([], arguments)
return Array.from(new Set(args))
}
combineUnquie([1, 2, 3, 4], [2, 4, 6])
实现Array.from()
Array.myFrom = (
function () {
// 是否可调用
const isCallable = function(fn) {
return typeof fn === 'function' || {}.toString.call(fn) === '[object Function]'
}
const toInt = function(value) {
const v = Number(value)
if (isNaN(v)) {
return 0
}
if (v === 0 || !isFinite(v)) {
return v
}
return (v > 0 ? 1 : -1) * Math.floor(Math.abs(v))
}
const maxSafeInt = Math.pow(2, 53) - 1
const toLength = function(value) {
const len = toInt(value)
return Math.min(Math.max(len, 0), maxSafeInt)
}
return function(arrayLike) {
const caller = this
if (arrayLike === null) {
throw new TypeError('Method `from` requires an array-like ')
}
const origin = Object(arrayLike)
let arg2
const mapFn = arguments.length > 1 ? arguments[1] : void undefined
if (typeof mapFn !== 'undefined') {
if (!isCallable(mapFn)) {
throw new TypeError('mapFn must be a function')
}
if (arguments.length > 2) {
arg2 = arguments[2]
}
}
const len = toLength(origin.length)
const arr = isCallable(caller) ? Object(new caller(len)) : new Array(len)
let i = 0
let val
while(i < len =) {
val = origin[i]
if (mapFn) {
arr[i] = typeof arg2 === 'undefined' ? mapFn(val, i) : mapFn.apply(arg2, [val, i])
} else {
arr[i] = val
}
i++
}
return arr
)()