扩展运算符(spread)是三个点(...)。它好比 rest
参数的逆运算,将一个数组转为用逗号分隔的参数序列。
console.log(...[1, 2, 3]) // 1 2 3
console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5
//该运算符主要用于函数调用
function add(x, y) {
return x + y
}
const numbers = [4, 38]
add(...numbers) // 42
扩展运算符的应用
1.复制数组
// ES5
const a1 = [1, 2]
const a2 = a1.concat()
a2[0] = 2
a1 // [1, 2]
// ES6
const a1 = [1, 2]
// 写法一
const a2 = [...a1]
// 写法二
const [...a2] = a1
2.合并数组
const arr1 = ['a', 'b']
const arr2 = ['c']
const arr3 = ['d', 'e']
// ES5 的合并数组
arr1.concat(arr2, arr3)
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
3.字符串
扩展运算符还可以将字符串转为真正的数组。
;[...'hello']
// [ "h", "e", "l", "l", "o" ]
Array.from()
: 用于将类似数组的对象和可遍历的对象转为真正的数组-
let arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3, } let arr2 = Array.from(arrayLike) // ['a', 'b', 'c']
Array.from 还可以接受第二个参数,作用类似于数组的
map
方法,用来对每个元素进行处理,将处理后的值放入返回的数组。 -
Array.from(arrayLike, (x) => x * x) // 等同于 Array.from(arrayLike).map((x) => x * x) Array.from([1, 2, 3], (x) => x * x) // [1, 4, 9]
join()
: 将数组的元素组起一个字符串,以separator
为分隔符,省略的话则用默认用逗号为分隔符,该方法只接收一个参数:即分隔符。
var arr = [1, 2, 3]
console.log(arr.join()) // 1,2,3
console.log(arr.join('、')) // 1、2、3
push()
: 可以接收任意数量的参数,把它们逐个添加到数组末尾,并返回修改后数组的长度。pop()
: 数组末尾移除最后一项,减少数组的length
值,然后返回移除的项。-
var arr = ['Kang', 'Ming', 'Wang'] var count = arr.push('Li') console.log(count) // 4 console.log(arr) // ["Kang", "Ming", "Wang", "Li"] var item = arr.pop() console.log(item) // Li console.log(arr) // ["Kang", "Ming", "Wang"]
map()
: 方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。-
const array1 = [1, 4, 9, 16] // pass a function to map const map1 = array1.map((x) => x * 2) console.log(map1) // expected output: Array [2, 8, 18, 32
filter()
: “过滤”功能,数组中的每一项运行给定函数,返回满足过滤条件组成的数组。-
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'] const result = words.filter((word) => word.length > 6) console.log(result) //["exuberant", "destruction", "present"]