es6 数组的拓展

1、拓展运算符

数组的拓展运算符为三个点(…),它的作用是将数中的值转为用逗号隔开的参数序列。

1.1

function fn (a,b) {

	console.log(a) //1
	console.log(b) //2
}

let arr = [1,2];

fn(…arr); //fn(…arr)其实等于fn(1,2)

1.2

let arr = [3,4];

let newArr = [1,2,...arr,5,6];

console.log(newArr)  //[1, 2, 3, 4, 5, 6]

1.3

let arr1 = [3,4];
let arr2 = ['a','b'];

拓展运算符后面还可以放表达式

let newArr = [1,2,...(false ? arr1:arr2),5,6];

console.log(newArr)  //[1, 2, "a", "b", 5, 6]

1.4、使用push方法的时候,可以方便地添加多个值。

let arr1 = [1,2]

let arr2 = [3,4,5,6]

arr1.push(...arr2)

console.log(arr1) //[1, 2, 3, 4, 5, 6]

1.5、对数组进行浅复制

let arr1 = [1,2,3]
let arr2 = [...arr1]

console.log(arr1) //[1, 2, 3]

同样的,这种方法也使用与合并数组

1.6 配合解构赋值

let [age,...arr] = [1,2,3,4,5]

console.log(age) //1
console.log(arr) //[2, 3, 4, 5]

注意…arr只能放在最后以为,否则会报错。

1.7、将字符串转为数组

var str = 'abcde';
console.log([...str]) //["a", "b", "c", "d", "e"]

2、Array.from方法

from方法可以将类似数组的对象,和可遍历的对象转为真正的数组。

比如NodeList集合还有arguments,都是类似数组的数组。不能直接使用数组的push等方法。

var arr = document.getElementsByTagName('div');

function fn () {
	console.log(arguments.push) //undefined
}

fn()

console.log(arr.push) //undefined

这种情况下,可使用from方法将它们转为真正的数组再调用方法。

var arr = document.getElementsByTagName('div');

function fn () {
	console.log(Array.from(arguments).push) //function
}

fn()

console.log(Array.from(arr).push) //function

2.1 from方法的第二个参数

from方法的第二个参数接收一个函数,可用来遍历数组中的元素。

let arr = [1,2,3,4];

let newArr = Array.from(arr, val => ++val)

console.log(newArr) //[2, 3, 4, 5]

猜你喜欢

转载自blog.csdn.net/weixin_40606003/article/details/83713313