06 数组的扩展

1. res 参数和扩展运算符
2. Array.from()与Array()
3.数组实例的 find() 和 findIndex()
4.数组实例的 fill()
5.数组实例的 entries() keys() values()
6.数组实例的 includes()
7.数组实例的 flat() flatMap()

1.res 参数和扩展运算符

rest参数的形式为:…变量名;扩展运算符是三个点(…数组)

  1. rest参数
  2. 扩展运算符
1.res 参数

rest参数用于获取函数的多余参数,这样就不需要使用arguments对象了。rest参数搭配的变量是一个数组,该变量将多余的参数放入数组中。

function add(...values) {
  let sum = 0

  for (var val of values) {
    sum += val
  }
  return sum
}

console.log(add(1,2,3)) //6

1.rest参数搭配的变量是一个数组,即…values的values是一个数组。
2.add(1,2,3)调用时,吧参数1,2,3放入了values数组。
3.总结一下:即把参数传入数组。

2.扩展运算符
扩展运算符可以看做是 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
console.log(...[1,2,3]) // 1 2 3

把数组[1,2,3]扩展为1 2 3

function add (x,y) {
  return x+y
}
var numbers = [4,38]
console.log(add(...numbers)) //42

把数组numbers扩展为4 38

var arr1 = [0,1,2]
var arr2 = [3,4,5]
arr1.push(...arr2) //把arr2扩展为参数push进数组arr1
console.log(arr1) // [0,1,2,3,4,5]

2.Array.from()与Array()

es6前的把其他类型转为数组对象时,使用的是Array()

var a = Array('hello')
a  // ["hello"]
a instanceof Array // true

Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。

Array.from('hello')  // ["h", "e", "l", "l", "o"]

3.数组实例的 find() 和 findIndex()

作用:找出某个符合条件的数组成员

  • find() 用于找出第一个符合条件的数组成员,参数是一个回调函数,找到返回value,找不到返回undefined。
  • findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1
[1,4,-5].find((n) => n<0) // -5
console.log(
  [1,5,10,15].findIndex(function(value, index, arr) {
    return value >9
  })
)  // 2

4.数组实例的 fill()

作用:填充数组

console.log(
  ['a','b','c'].fill(7)
)

console.log(
  ['a','b','c'].fill(7,1,2)
)

fill(value,[start],[end])。

数组实例的 entries() keys() values()

  • entries()对键值对遍历
  • keys() 对键名遍历
  • values() 对键值遍历
for (let index of ['a','b'].keys()) {
  console.log (index)  // 0 1
}
for (let index of ['a','b'].entries()) {
  console.log (index)  // [ 0, 'a' ] [ 1, 'b' ]
}
for (let index of ['a','b'].values()) {
  console.log (index)  // a b
}

6.数组实例的 includes()

作用:
判断数组是否包含 给定的值,第二个参数表示查询起点

[1, 2, 3].includes(2)  // true
[1, 2, 3].includes(2,-1) //false
[1, 2, 3].includes(2,-2) // true

在这个方法之前,我们一直用的是indexof(),字符串实例也有这个方法。

[1,2,3].indexOf(1) // 0
'abc'.indexOf('c') // 2

7.数组实例的 flat() flatMap()

  • flat() 转为一维数组
  • flatMap() 执行一个函数再转为一维数组
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值