熟悉Array.from()

语法:Array.from(arrayLike[, mapFn[, thisArg]])

返回值:一个新的数组实例。

Array.from() 方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。

arrayLike想要转换成数组的伪数组对象或可迭代对象。mapFn 可选如果指定了该参数,新数组中的每个元素会执行该回调函数。thisArg 可选可选参数,执行回调函数 mapFnthis 对象。

从String生成数组

Array.from('foo');// [ "f", "o", "o" ]

从Set生成数组

const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);// [ "foo", "bar", "baz" ]

从Map生成数组

const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];

Array.from(mapper.keys());
// ['1', '2'];

从类数组对象(arguments)生成数组

function f() {
  return Array.from(arguments);
}

f(1, 2, 3); // [ 1, 2, 3 ]

Array.from()使用箭头函数

// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]

// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

数组去重合并

function combine(){
    let arr = [].concat.apply([], arguments);  //没有去重复的新数组
    return Array.from(new Set(arr));
}

var m = [1, 2, 2], n = [2,3,3];
console.log(combine(m,n));// [1, 2, 3]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值