Array
Array.of()
如果要实现一个将方法参数arguments变成数组的功能,你会怎么实现?
Array.prototype.slice.call(arguments)
- Array.of
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]
分类:
ES学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?