es6 数组的扩展

1.扩展运算符

扩展运算符是三个点“…”,等价 于函数扩展上的reset参数的逆运算,即为将一个数组转为用逗号分隔的参数序列。

	let a=[12,3,4];
	let b=[...a];
	console.log(b);//输出:1 2 3 4
    
    let fun=(...values)=>{
    	console.log(values);//输出:[1,2,3,4,5]
    }
    fun(1,2,3,4,5);

2.在类数组中使用扩展运算符

	let btn = document.getElementsByClassName('btn');
    console.log(...btn);

3.获取数组中的最大值

	let arr1 = [9, 1, 3, 2, 5, 4];
    let max = Math.max(...arr1);
    console.log(max);//输出:9

4.使用concat合并两个数组

	let a2 = [1, 2, 3];
    let b2 = a2.concat();
    console.log(b2);
    b2[0] = 10;
    console.log(a2);//输出:10,2,3

5.使用扩展运算符合并数组

	let a2 = [1, 2, 3];
    let a3 = [4, 5, 6];
    let a4 = [7, 8, 9];
    console.log([...a2, ...a3, ...a4]);

6.用Array.from()将类数组转化为数组

	let btnlist = document.getElementsByClassName('btn');
    console.log(Array.from(btnlist));

7.用 Array.of()将一组值转化为数组

	console.log(Array.of(1, 2, 3, 4, 5, 6));
    console.log(Array.of.call(null, 1, 2, 3, 4, 5, 6));
    console.log(Array.of.apply(null, [1, 2, 3, 4, 5, 6]));

8.用copyWithin()方法复制数组元素

参数一:target-从中复制元素的索引位置。

参数二:begin-开始复制元素的索引。这是一个可选参数。

参数三:end-结束复制元素的索引。这是一个可选参数。

	let list = [1, 2, 3, 4, 5];
	let info = list.copyWithin(0, -2, -1);
    console.log(info);

9.用find()方法返回第一个满足条件的值

	let item = [1, 2, 3, 4, 5, 6];
    let result = item.find((value, index, arr) => {
    	return value % 7 == 0;
    });
    console.log(result);//未找到输出:undefined

10.用findIndex()方法返回的是满足条件的第一个值的索引

	let item = [1, 2, 3, 4, 5, 6];
	let index = item.findIndex((item, index, arr) => {
		return item % 7 == 0;
	});
	console.log(index);//输出:-1

11.使用fill()方法使用给定的值填充数组

	let item = [1, 2, 3, 4, 5, 6];
	console.log(item.fill('a'));
    console.log(item.fill('b', 0, 3));//参数分别为:value  start  end

12.使用entries()、keys()和values()方法遍历数组

它们都返回一个遍历器对象,区别为:
keys()是对键名的遍历
values()是对键值的遍历
entries()是对键值对的遍历

	let tea = [1, 2, 3, 4, 5];
	for (let key of tea.keys()) {
    	console.log(key);
    }
    for (let key of tea.values()) {
    	console.log(key);
    }
    for (let item of tea.entries()) {
    	console.log(item);
    }

13.使用includes()方法检索数组里面是否包含某个值

	let da = [1, 2, 3, 4, 5];
    console.log(da.includes(1));//true
    console.log(da.includes(1, 2));//false
    console.log(da.includes(1, -5));//false

14.使用flat()方法降数组维度

	let k = [1, 2, 3, [4, 5], [[5, 6, 7], [8, 9, [10, 11, [12, 13]]]]];
	console.log(k.flat(4));

15.使用flatMap()方法映射数组

	let m=[1,2,3,4,5];
    let rm=m.flatMap((value,index,item)=>{
    	return [[value*2]];
    });
     console.log(rm)

16.使用sort()方法对数组从小到大排序

	let mk = [9, 3, 4, 2, 1, 5];
    console.log(mk.sort());//默认从小-大
    console.log(mk.sort((x, y) => {
    	return Math.random() - 0.5;
    }));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值