What new extensions are added to arrays in ES6?

1. Application of spread operator

 ES6 converts an array into a comma-separated parameter sequence by expanding element symbols , ...such  as the inverse operation of parameters.rest

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

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

[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]

Mainly used when calling functions, turning an array into a parameter sequence

function push(array, ...items) {
  array.push(...items);
}

function add(x, y) {
  return x + y;
}

const numbers = [4, 38];
add(...numbers) // 42

Certain data structures can be converted into arrays

[...document.querySelectorAll('div')]

Enables easier implementation of array copying

const a1 = [1, 2];
const [...a2] = a1;
// [1,2]

The merging of arrays is also more concise

const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]

Note: A shallow copy is implemented through the spread operator. Modification of the value pointed to by the reference will be reflected in the new array synchronously.

It will be clearer if you look at an example below.

const arr1 = ['a', 'b',[1,2]];
const arr2 = ['c'];
const arr3  = [...arr1,...arr2]
arr[1][0] = 9999 // 修改arr1里面数组成员值
console.log(arr[3]) // 影响到arr3,['a','b',[9999,2],'c']

The spread operator can be combined with destructuring assignment to generate arrays

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   // []

If the spread operator is used for array assignment, it can only be placed at the last position of the parameter, otherwise an error will be reported.

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

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

You can convert a string into a real array

[...'hello']
// [ "h", "e", "l", "l", "o" ]

Objects that define the Iterator interface can be converted into real arrays using the spread operator.

let nodeList = document.querySelectorAll('div');
let array = [...nodeList];

let map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);

let arr = [...map.keys()]; // [1, 2, 3]

If you use the spread operator on an object without an Iterator interface, an error will be reported.

const obj = {a: 1, b: 2};
let arr = [...obj]; // TypeError: Cannot spread non-iterable object

2. New methods added to the constructor

Regarding the constructor, the new methods added to the array are as follows:

  • Array.from()
  • Array.of()

Array.from()

Convert two types of objects into real arrays: array-like objects and traversable (iterable)objects (including  ES6 new data structures  Set and  Map)

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

You can also accept a second parameter to process each element and put the processed value into the returned array.

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

Array.of()

Used to convert a set of values ​​into an array

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

When there are no parameters, an empty array is returned.

When there is only one parameter, it actually specifies the length of the array.

When the number of parameters is no less than 2, Array()a new array composed of parameters will be returned.

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

 

3. New methods added to instance objects

The new methods for array instance objects are as follows:

  • copyWithin()
  • find()、findIndex()
  • fill()
  • entries(),keys(),values()
  • includes()
  • flat(),flatMap()

copyWithin()

Copies the members at the specified location to other locations (the original members will be overwritten), and then returns the current array

The parameters are as follows:

  • target (required): The position from which data should be replaced. If it is a negative value, it represents the reciprocal value.
  • start (optional): Start reading data from this position, the default is 0. If it is a negative value, it means counting from the end.
  • end (optional): Stop reading data before reaching this position. The default is equal to the array length. If it is a negative value, it means counting from the end.
[1, 2, 3, 4, 5].copyWithin(0, 3) // 将从 3 号位直到数组结束的成员(4 和 5),复制到从 0 号位开始的位置,结果覆盖了原来的 1 和 2
// [4, 5, 3, 4, 5] 

find()、findIndex()

find()Used to find the first array member that meets the criteria

The parameter is a callback function that accepts three parameters: the current value, the current position and the original array.

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

findIndexReturns the position of the first array member that meets the criteria, or if none of the members meet the criteria-1

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

Both methods can accept a second parameter, thisan object used to bind the callback function.

function f(v){
  return v > this.age;
}
let person = {name: 'John', age: 20};
[10, 12, 26, 15].find(f, person);    // 26

fill()

Fills an array with given values

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

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

Also accepts second and third parameters to specify the starting and ending positions of the padding

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

Note that if the filled type is an object, it is a shallow copy

entries(),keys(),values()

keys()It is a traversal of key names, values()key values, and entries()key value pairs.

or (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"

includes()

Used to determine whether an array contains a given value

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

The second parameter of the method indicates the starting position of the search, which defaults to0

If the parameter is a negative number, it indicates the position of the reciprocal

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

flat(),flatMap()

Flatten the array and return a new array without affecting the original data.

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

flat()By default, only one layer will be "flattened". If you want to "flatten" a multi-layered nested array, you can write the flat()parameter of the method as an integer, indicating the number of layers you want to flatten. The default is 1

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

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

flatMap()The method executes a function on each member of the original array, which is equivalent to executing Array.prototype.map(), and then executes flat()the method on the array composed of the return value. This method returns a new array without changing the original array

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

flatMap()The method can also have a second parameter, which is used to bind the traversal functionthis

4. Spaces in the array

A gap in an array means that there is no value in a certain position of the array.

ES6 explicitly converts gaps to undefined, including Array.from, spread operators, copyWithin(), fill(), entries(), keys(), values(), find()andfindIndex()

It is recommended that you avoid gaps in your daily writing

5. Sorting stability

Set sort()default to stable sorting algorithm

const arr = [
  'peach',
  'straw',
  'apple',
  'spork'
];

const stableSorting = (s1, s2) => {
  if (s1[0] < s2[0]) return -1;
  return 1;
};

arr.sort(stableSorting)
// ["apple", "peach", "straw", "spork"]

In the sorted results, strawin sporkfront of is consistent with the original order.

Guess you like

Origin blog.csdn.net/zz130428/article/details/130800143