JavaScript 中 ES6-Array 简介及方法

  1. 扩展运算符

扩展运算符(spread)是三个点(...)。将一个数组转为用逗号分隔的参数序列。

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

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

其中,合并数组:

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' ]

  1. Array.from()

   将两类对象转换为数组:1.类似数组的对象(array-like object)

                         2.可遍历的对象(iterable)  

let arrayLike = {

    '0': 'a',

    '1': 'b',

    '2': 'c',

    length: 3};

// ES6 的写法let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']                        

Array.from(arrayLike, x => x * x);// 等同于

Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)// [1, 4, 9]

  1. Array.of()

   将一组值转换为数组,同时弥补Array()的不足(只有当参数个数不少于 2 个时,Array()才会返回由参数组成的新数组。

Array() // []

Array(3) // [, , ,]

Array(3, 11, 8) // [3, 11, 8]

Array.of() // []

Array.of(undefined) // [undefined]

Array.of(1) // [1]

Array.of(1, 2) // [1, 2]

  1. copyWithin()

   修改当前数组:在数组内部将指定数组覆盖到其他数组上。基本语法:

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

   其中target(必需):从该位置开始替换数据。若为负,表示倒数;

       start(非必需):从该位置开始读取数据,默认为0。若为负,逆向计数,       从1开始。

   end(非必需):到该位置前停止读取数据,默认为数组长度。若为负,同start。

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

// -2相当于3号位,-1相当于4号位[1, 2, 3, 4, 5].copyWithin(0, -2, -1)// [4, 2, 3, 4, 5]

// 对于没有部署 TypedArray 的 copyWithin 方法的平台// 需要采用下面的写法[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);// Int32Array [4, 2, 3, 4, 5]

  1. find(),findIndex()

   find()用于找到第一个符合条件的数组成员。findIndex()用于返回第一个满足条件的数组成员的地址。

[1, 5, 10, 15].find(function(value, index, arr) {

  return value > 9;}) // 10

[1, 5, 10, 15].findIndex(function(value, index, arr) {

  return value > 9;}) // 2

  1. fill()

   用于填充数组。其中,如果填充的类型为对象,那么被赋值的是同一个内存地址的对象,而不是深拷贝对象。

new Array(3).fill(7)// [7, 7, 7]

['a', 'b', 'c'].fill(7, 1, 2)// ['a', 7, 'c']类似于copyWithin()

let arr = new Array(3).fill({name: "Mike"});

arr[0].name = "Ben";

arr// [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}]

let arr = new Array(3).fill([]);

arr[0].push(5);

arr// [[5], [5], [5]]

  1. entries()

   可以与for...of...一起用来循环进行遍历。其中keys()是对键的遍历,values()是对值的遍历,entries()是对键值对的遍历。

for (let [index, elem] of ['a', 'b'].entries()) {

  console.log(index, elem);}// 0 "a"// 1 "b"

  1. includes()

   返回一个布尔值,用于返回数组中是否包含给定的值。若拥有第二个参数,表示搜索的起始位置,若为负,则逆向。另外,Map 和 Set 数据结构有一个has方法需要注意与includes区分。Map 结构的has方法,是用来查找键名的,比如Map.prototype.has(key)Set 结构的has方法,是用来查找的,比如Set.prototype.has(value)

  1. falt(),flatMap()

 flat()默认“拉平”一层数组,若需具体层数,如拉两层,则为flat(2),若未知且最终全转换为一维数组,则为flat(Infinity)。flat()会跳过空位。flatMap()对原数组的每个成员执行一个函数,但是flatMap只能“拉开”一层数组。

[1, [2, [3]]].flat(Infinity)// [1, 2, 3]

[2, 3, 4].flatMap((x) => [x, x * 2])// [2, 4, 3, 6, 4, 8]

[1, 2, 3, 4].flatMap(x => [[x * 2]])// [[2], [4], [6], [8]]

  1. toReversed(),toSorted(),toSpliced(),with()
  1. 用来颠倒数组成员的位置;
  2. 用来对数组成员进行正向排序;
  3. 用在指定位置,更换指定数量的成员;
  4. 同3                                                         注意:reserve(),sort(),splice(),splice(index,1,value)与上述四个新方法的含义和用法完全相同,但是新方法不会改变原数组。

[1, 8, 5].sort((a, b) => {

  return a-b; // 从小到大排序若为b-a,则为从大到小排序

});

const myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

const deleted = myFish.splice(2, 0, 'drum'); // 在索引为2的位置插入'drum'// myFish 变为 ["angel", "clown", "drum", "mandarin", "sturgeon"],deleted为[]

const sequence = [1, 2, 3];

sequence.toReversed() // [3, 2, 1]

sequence // [1, 2, 3]

const outOfOrder = [3, 1, 2];

outOfOrder.toSorted() // [1, 2, 3]

outOfOrder // [3, 1, 2]

const array = [1, 2, 3, 4];

array.toSpliced(1, 2, 5, 6, 7) // [1, 5, 6, 7, 4]

array // [1, 2, 3, 4]

const correctionNeeded = [1, 1, 3];

correctionNeeded.with(1, 2) // [1, 2, 3]

correctionNeeded // [1, 1, 3]

  1. group(),groupToMap()

   group()是一个分组函数,其返回值是字符串(若不是,会自动转换成字符串),以作为分组后的组名。groupToMap()相较于group()唯一区别是返回值是一个Map结构,意味着不管分组函数返回什么值,都会直接作为组名而不用强制转换为字符串型。

const array = [1, 2, 3, 4, 5];

array.group((num, index, array) => {

  return num % 2 === 0 ? 'even': 'odd';});// { odd: [1, 3, 5], even: [2, 4] }

const array = [1, 2, 3, 4, 5];

const odd  = { odd: true };const even = { even: true };

array.groupToMap((num, index, array) => {

  return num % 2 === 0 ? even: odd;});//  Map { {odd: true}: [1, 3, 5], {even: true}: [2, 4] }

  1. every(),some()

   every检测每一个元素是否通过了callback测试,返回布尔值。some不同的在于只要存在至少一个元素满足callback测试,就返回true。

[2, 5, 8, 1, 4].some(item => item > 6); // true

  1. filter()

   返回一个新数组,其中满足callback测试的返回,若均不满足,则返回false。

const filtered = [1, 2, 3].filter(element => element > 1);

// filtered: [2, 3];

  1. pop(),shift()

pop()删除数组最后一个元素,同时返回最后一个元素的值,若数组为空,则返回undefined。shift()删除数组第一个元素,同时返回该值,若为空同上。

[1, 2, 3].pop();// 3

const shifted = ['one', 'two', 'three'].shift();// shifted: 'one'

  1. push(),unshifted()

push()将n个元素添加到数组末尾(n>=1),同时返回新数组的长度。unshifted()添加到数组开头,并返回新数组长度。

  1. reduce()

对数组中的每个元素依次执行callback累加,使其减少为单个值。

const total = [0, 1, 2, 3].reduce((sum, value) => {

  return sum + value;

}, 0);

// total is 6

const newArray = [{ name: 'aa', age: 1 }, { name: 'bb', age: 2 }, { name: 'cc', age: 3 }].reduce((arr, element) => {

  if (element.age >= 2) {

    arr.push(element.name);

  }

  return arr; // 必须有return,因为return的返回值会被赋给新的累加器,否则累加器的值会为undefined。

}, []);

// newArray is ["bb", "cc"];

  1. slice()

返回一个数组,包含原数组从begin到end(不包含end)的索引位置的所有元素。

const newArray = ['zero', 'one', 'two', 'three'].slice(1, 3);// newArray: ['one', 'two'];

  1. join(seperator)

将数组中的元素通过seperator连接成字符串,并返回该字符串,seperator的初始默认值为“,”。

[1, 2, 3].join(';');// "1;2;3"

  1. forEach()

为每个数组调用一次callback。

var txt = "";

var numbers = [45, 4, 9];

numbers.forEach(myFunction);

function myFunction(value, index, array) {

  txt = txt + value + "<br>";

}//45

   4

   9

20.map()

返回一个新数组,新数组中的每个元素都是调用callback函数后返回的结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值