Array.of()
如果要实现一个将方法参数arguments变成数组的功能,你会怎么实现?
Array.prototype.slice.call(arguments)
Array.of(1, 2, 3); // [1, 2, 3]
if (!Array.of) {
Array.of = function() {
return Array.prototype.slice.call(arguments);
};
}
Array.from()
语法
Array.from(arrayLike[, mapFn[, thisArg]])
- arrayLike是要转换成数组的伪数组对象或者可迭代对象
- maFn如果指定此参数,新数字的每个元素会执行该回调函数
- thisArg可选参数,执行回调函数mapFn时this对象
- returns:一个新的数组实例
实现一个对类似数组或者可迭代对象的浅拷贝
const array=[1,2,3,4]
const newArray=Array.from(array)// Array [1,2,3,4]
console.log(array===newArray)//false
console.log(Array.from('foo'))//Array['f','o','o']
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);//['foo', 'bar', 'baz', 'foo']
const map=new Map([['name','marvin'],['age','18']])
Array.from(map);//[['name','marvin'],['age','18']]
function f() {
return Array.from(arguments);
}
f(1,2,3)//[1,2,3]
箭头函数
Array.from([1,2,3],x=>2*x)//[2, 4, 6]
Array.from({length: 5}, (v, i) => i);//[0,1,2,3,4] 数组递增
序列生成器实现
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
数组合并去重
function combine(){
let arr=[].concat.apply([],arguments)
return Array.from(new Set(arr))
}
combine([1,2,3],[2,3,4]);//[1,2,3,4]
MDN参考地址