ES6数组方法

本系列属于阮一峰老师所著的ECMAScript 6 入门学习笔记


拓展运算符

拓展运算符...用于将一个数组转为用逗号分隔的参数序列

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

// 函数调用
function f(x, w, x, y, z) {
  return x + y + x + w + z
}
f(1, ...arr, 2, ...[3]) // 17

// 后置表达式
let x = 1
const arr1 = [...(x > 0 ? ['a'] : ['b']), 'c'] // ["a", "c"]
const arr2 = [...(x < 0 ? ['a'] : ['b']), 'c'] // ["b", "c"]

[...[], 1] // [1]

// 替换ES5中apply
function f(x, y, z) {
  console.log(x, y, z)
}
var args = [1, 2, 3]
// ES5
f.apply(null, args) // 1 2 3
// ES6
f(...args) // 1 2 3

// push数组
var arr1 = [0, 1, 2]
var arr2 = [3, 4, 5]
arr1.push(...arr2) // [0, 1, 2, 3, 4, 5]

// date设置
new Date(...[2015, 0, 1]) // Thu Jan 01 2015 00:00:00 GMT+0800 (中国标准时间)

// 合并数组
var arr1 = ['a', 'b']
var arr2 = ['c']
var arr3 = ['d', 'e']

console.log([...arr1, ...arr2, ...arr3]) // ["a", "b", "c", "d", "e"]

// 与结构赋值结合 用于数组赋值只能放在最后一位
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest  // [2, 3, 4, 5]

const [first, ...rest] = [];
first // undefined
rest  // []

const [first, ...rest] = ["foo"];
first  // "foo"
rest   // []

const [...butLast, last] = [1, 2, 3, 4, 5] // 报错
const [first, ...middle, last] = [1, 2, 3, 4, 5]  // 报错

// 字符串转化
[...'hello'] // ["h", "e", "l", "l", "o"]

// 正确识别32位Unicode字符的长度
let str = 'x\uD83D\uDE80y'
[...'x\uD83D\uDE80y'].length // 3
[...str].reverse().join('') // 'y\uD83D\uDE80x'
Array.from()

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

Array.from({ length: 2 }) // [undefined, undefined]
{ '0': 'a', '1': 'b', length: 2 }) // ["a", "b"]
Array.from('hello') // ["h", "e", "l", "l", "o"]

// 接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组
Array.from([1, 2, 3], (x) => x * x)
// 把原始的数据结构转换为规范的数组结构,然后利用众多数组方法对其进行处理
Array.from({ length: 2 }, () => 'jack') // ["jack", "jack"]
// 处理各种Unicode字符,并且正确返回其长度
function f(string) {
  return Array.from(string).length
}
Array.of()

Array.of 方法用于将一组值,转换为数组,该方法主要用来弥补数组构造函数Array() 的不足。

Array.of(3,11,8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
copyWithin()

数组实例的copyWithin方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。

Array.prototype.copyWithin(target, start = 0, end = this.length)

它接受三个参数。

  • target(必需):从该位置开始替换数据。
  • start(可选):从该位置开始读取数据,默认为0。如果为负值,表示倒数。
  • end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。

这三个参数都应该是数值,如果不是,会自动转为数值。

// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]
find()

find 方法用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员一次执行该回调函数,直到找到第一个返回值为true的成员,然后返回该成员。如果没有符合条件的,则返回undefined

[1, 5, 10, 15].find(function(value, index, arr) {
  return value > 9;
}) // 10

find方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。

findIndex()

findIndexfind 方法很类似,用于返回第一个符合条件的数组成员位置。如果所有成员都不符合,则返回-1

[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2
fill()

fill 方法使用指定值,填充一个数组

['a','b','c'].fill(1) // [1,1,1]
new Array(3).fill(1) // [1,1,1]
// 接收第二个和第三个参数,用于指定填充的其实位置和结束位置
['a', 'b', 'c'].fill(7, 1, 2) // ['a', 7, 'c']
entries() , keys() , values()

这三个方法用于遍历数组,返回一个遍历器对象,可以用for...of 循环进行遍历,keys 是对键名的遍历,values 是对键值的遍历,entries 是对键值对的遍历

// 使用for...of进行遍历
for(let index of ['a','b'].keys()){
    console.log(index)
}
// 0
// 1
for(let val of ['a','b'].values()){
    console.log(val)
}
// 'a'
// 'b'
for(let [index,val] of ['a','b'].entries()){
    console.log(index,val)
}
// 0 'a'
// 1 'b'

// 手动调用遍历器对象的next方法
let entries = ['a','b','c'].entries()
console.log(entries.next().value) // [0, 'a']
console.log(entries.next().value) // [1, 'b']
console.log(entries.next().value) // [2, 'c']
includes()

includes 方法返回一个布尔值,表示某个数组是否包含特定的值

[1,2,3].includes(2) //true
// 支持第二个参数,表示搜索的其实位置
[1,2,3].includes(3,3) // false
[1,2,3].includes(3,-1) // true
// 可以很方便的替换indexOf的功能

转载于:https://www.cnblogs.com/pengzhixin/p/7563254.html

ES6引入了一系列新的数组处理方法,极大地丰富了数组操作的工具箱,使得数组操作更加灵活和高效,以下是一些常见的ES6数组方法介绍: - **map()**:`forEach()`类似,会遍历数组的每个元素,对每个元素执行提供的函数,并返回一个新数组,新数组中的元素是原数组元素经过函数处理后的结果。示例如下: ```javascript let arr = [1,2,3,4,5]; arr.map( (value,index,array) => { value = value * 2; console.log(`value:${value} index:${index} array:${array}`); }); console.log(arr); ``` - **filter()**:作为过滤器,用于筛选符合条件的元素,返回一个新数组,新数组包含所有满足条件的元素。示例如下: ```javascript let arr1 = [12,4,68,97,35,98]; let arr2 = arr1.filter(function(value,index,array){ // 筛选大于20的数字 // return value >= 20; // 筛选偶数 return value % 2 === 0; }); console.log(arr2); ``` - **some()**:用于查找数组中是否包含满足条件的元素,返回一个布尔值。当查找到第一个满足条件的值时就终止循环。示例如下: ```javascript let arr3 = ['pink','red','yellow','blue','purple','black']; let some = arr3.some(function(value,index,array){ return value === 'pink'; }); console.log(some); ``` - **find()**:用于查找数组中第一个满足条件的元素,若找到则返回该元素,若未找到则返回`undefined`。示例如下: ```javascript const numbers = [1, 2, 3, 4, 5]; const found = numbers.find(element => element > 3); console.log(found); // 4 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值