ES 6 数组的扩展

扩展运算符(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"]
    

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值