[JavaScript] Explore the array API in ES6: simple and efficient operation method

ES6( ECMAScript 2015) is JavaScriptan important version of the language, which provides many new features and APIs for writing more concise, convenient and readable code. If you want to know about all the new APIs in ES6, you can jump to my other blog: New features of JS syntax ES6, ES7, ES8, ES9, ES10, ES11, ES12

The array-related APIs have also been greatly enhanced in ES6. Let me introduce the new features and APIs of arrays in ES6 in detail.

1. Array.of()

Array.of()The method creates a new array and creates array elements based on the passed parameters.

  • The parameters passed in can be of any data type, and the array length does not need to be specified.
  • If there are no parameters, an empty array is returned
  • The behavior of Array.of() is more unambiguous and predictable than traditional array literal creation.

For example, you can create an array with three elements as follows:

const arr = Array.of(1, 2, 3);
console.log(arr);  // output: [1, 2, 3]

In this example, we create an array of three integers using the Array.of() method and assign it to the variable arr. Note that since we passed three parameters, the array created contains three elements.

Array.of()The main advantage of the method is that it creates an array of a specified length without having to use the special syntax of the Array() method. For example, if you want to create an array with five elements, you can do this:

const arr = Array.of(5);
console.log(arr);  // output: [5]

In this example, we passed an integer 5, which will create an array containing one element with the value 5. Note that this is different from how it is created using the Array() method:

const arr = new Array(5);
console.log(arr);  // output: [ , , , , ]

In this example, we create an array with five elements and assign it to the variable arr. Note that when created, this array is given no element values. This is different from using the Array.of() method, which initializes an array with any number of arguments, so if you want to set the value, you can do it in automatic list form:

const arr = Array.of(1, 2, 3, 4, 5);
console.log(arr);  // output: [1, 2, 3, 4, 5]

Also, be aware of the use of the Array.of() method when creating elements that contain a string. In this case, the string is treated as a single element rather than splitting the string into individual characters.

const arr = Array.of("hello");
console.log(arr);  // output: ["hello"]

In summary, Array.of()methods provide a simple way to create a custom-sized array and initialize the elements within it.

2. Array.from()

Array.from()Method creates a new array instance from an array-like or iterable object such as a Set or Map. This method also supports implicit mapping and filter parameters.

For example, to mySetcreate an array from a Set object, use the following:

const mySet = new Set([1, 2, 3]);
const arr = Array.from(mySet);
console.log(arr); // [1, 2, 3]

Implicit mapping can be accomplished using the second parameter, which receives a function to map elements:

const arr = Array.from([1, 2, 3], x => x * 2);
console.log(arr); // [2, 4, 6]

3. Array.prototype.fill()

Array.prototype.fill()Method replaces all elements in the array with the specified value. It accepts three parameters: value( required ), start( optional ) and end( optional ).

  • valueThe parameter is the value used to fill the array elements.
  • startThe parameter indicates the starting position of filling. If not specified, the default is 0.
  • endThe parameter represents the end position of the padding, but does not include the end position itself. If the end parameter is not passed, the default is the end of the array.

For example, we can use the fill() method to set all elements in an array to the same value :

// 创建一个5个元素的空数组
const arr = new Array(5);

// 用数字0填充数组
arr.fill(0);

console.log(arr);  // output: [0, 0, 0, 0, 0]

As shown above, we first create an empty array with 5 elements and assign it to the variable arr. Next, we use fill()the method to set all elements in the array to the number 0.

The following example demonstrates using the start and end parameters to fill a specific subset of an array :

// 创建一个5个元素的空数组
const arr = new Array(5);

// 用数字1来填充数组的第2个到第4个元素
arr.fill(1, 1, 4);

console.log(arr);  // output: [ , 1, 1, 1, ]

As shown above, we first initialize an empty array with 5 elements and assign it to the variable arr. Next, we use fill()the method to set the 2, th 3and th 4elements of the array to numbers 1, specifying a start parameter of 1 (indicating the second element) and an end parameter of 4 (indicating the index of the fifth element).

It is worth mentioning that,

  • fill()The method operates on 原数组and returns a modified array , so there is no need to create a new array.
  • If you need to create a new array, you can use a combination of Array.from()the method andfill() the method :
const n = 5;
const arr = Array.from({
    
    length: n}, () => 0);
console.log(arr);  // output: [0, 0, 0, 0, 0]

In the above example, we use the Array.from() method and an arrow function to generate an array of length n and fill it with 0 to obtain a new array containing n elements.

In summary, Array.fill()methods provide a quick way to set element values ​​of large arrays, and it allows easy manipulation of raw arrays.

4. Array.prototype.copyWithin()

Array.copyWithin()This method copies the contents of a given array to another location, overwriting it with the values ​​in the original array . It accepts three parameters: target, start and end.

  • targetRepresents the subscript index copied to this location,

  • startand endrepresent the start and end positions of the part that needs to be copied (the element at the start position will be included in the copied part, and the element at the end position will not be included).

      如果有需要,方法会在进行拷贝操作前将数组缩小或扩大为所需大小。
    

The following example demonstrates how to use copyWithin()the method:

const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3, 4);
console.log(arr);  // output: [4, 2, 3, 4, 5]

As shown above, we first define an array of 5 integers and assign it to a variable arr. Then, we use arr.copyWithin()the method to copy an item starting from the array index 3to the array index 0, overwriting the original one 前三项. This copyWithin() method will 原数组operate on , which is why the copied value starts from the first position of the original array.

Let's explain the parameters of this method in detail:

  • target: Required parameter. Start replacing data from this position. If it is a negative number, it means starting from array.length + target (that is, counting backwards from the end of the array).
  • start: Required parameter. Start reading data from this position, the default is 0. If it is a negative number, it means reading from array.length + start (that is, counting backwards from the end of the array).
  • end: Optional parameter. Stop reading data before reaching this position. The default is array.length. If it is a negative number, it means to stop reading from array.length + end (that is, counting backwards from the end of the array).

have to be aware of is:

  • targetThe , startand endparameters must all be integers , otherwise they will be automatically rounded.
  • This method cannot be used on constdeclared arrays because it modifies the original array .

In summary, Array.copyWithin()methods provide a fast way to swap, move, and copy array elements .

5. Array.prototype.find() 和 Array.prototype.findIndex()

  • Array.prototype.find()The method is used to find the first array element that meets the conditions and return the element. Similarly,
  • Array.prototype.findIndex()The method can also find the first element that meets the condition and return the index of that element. If no matching element is found, it is returned undefined.

For example, to find [1,2,3,4,5]the first number greater than 3 in an array, you can use the following method:

const arr = [1,2,3,4,5];
const index = arr.find(item => item > 3);
const index2 = arr.findIndex(item => item > 3);
console.log(index);  // 4
console.log(index2); // 3

6. Array.prototype.some() 和 Array.prototype.every()

  • Array.prototype.some()Method checks whether one or more elements in the array meet the criteria. This method returns a Boolean value of true or false. -
  • Array.prototype.every()The method checks whether all elements in the array meet the conditions. If the condition is met, it returns true, otherwise it returns false.

For example, to check [2, 3, 4, 5]whether there is a number greater than 3 in the array, you can use the following method:

const arr = [2,3,4,5];
const hasGreaterThanThree = arr.some(item => item > 3);
const allGreaterThanOne = arr.every(item => item > 1);
console.log(hasGreaterThanThree); // true
console.log(allGreaterThanOne);  // true

7. Array.prototype.flat()

Array.prototype.flat()The method is used to recursively expand an array, turning the nested array into a one-dimensional array. The default expansion depth of this method is 1, and can accept an optional integer parameter indicating the depth of expansion. If the argument is Infinity, then the recursion will be executed until expanded into a one-dimensional array.

For example, to [[1,2,3],[4,5]]expand a nested array into a one-dimensional array, you can use the following method:

const arr = [[1,2,3],[4,5]];
const flattened = arr.flat();
console.log(flattened); // [1, 2, 3, 4, 5]

If you already know how many layers to expand, you can pass the value as a parameter to flatthe method:

For example, [[1,[2,3]],[4,[5,6]]]expand a nested array into a one-dimensional array:

const arr = [[1,[2,3]],[4,[5,6]]];
const flattenedOnce = arr.flat(1);
console.log(flattenedOnce); // [1, [2, 3], 4, [5, 6]]
const flattenedTwice = arr.flat(2);
console.log(flattenedTwice); // [1, 2, 3, 4, 5, 6]

It should be noted that flat()the method does not change the original array, but returns a new array , which is suitable for contexts that do not change the original data. If the original array contains nullor undefined, they will be automatically skipped.

Another thing to note is that flat()although the method is convenient, it may also cause performance problems and logic problems . For very deeply nested arrays, if you use flat()the method directly, the readability and maintainability of the code will be lost . If there are nested arrays of uncertain depth, it is best to use a recursive method to expand the array, or use a third-party library to avoid performance and logic problems during expansion.

8、Array.prototype.flatMap()

Array.prototype.flatMap()The method is a new array method introduced under the ES2019 standard, which combines the functions of the Array.prototype.map()and Array.prototype.flat()methods. The method can " flatten " the array into a new array flatMap()according to certain rules , which is very similar to the flat() method, but more flexible than.flat()

flatMap()The method first uses the method to operate on the array elements according to the specified rules, and then " flattensmap() " the processed array into a one-dimensional array. The difference from the map() and flat() methods is that the flatMap() method combines these two operations, avoiding the need to write additional code when using map() and flat().

For example, if we have an array and want to multiply each element by 2 and then take out the even values , we can use the following method:

const arr = [1, 2, 3, 4];
const result = arr.flatMap(x => x * 2).filter(x => x % 2 === 0);
console.log(result); // [4, 8]

In the above code, we first map()multiply each element in the array using the method 2, then flat()expand the result into a one-dimensional array using the method, and filter()filter out the even values ​​using the method.

have to be aware of is,

  • flatMap()The method skips array elements with values ​​of nullor undefined, resulting in clearer and more concise code without having to consider these two elements.
  • flatMap()Methods may occur in some situations 越界异常的问题, so when using them, you need to pay due attention to issues such as range out of bounds.

9. Array.prototype.keys()、Array.prototype.entries()和Array.prototype.values()

Three iteration methods are added to the array prototype in ES6: keys(), entries()and values().

Array.prototype.keys()Method returns an iterator containing the index of each element in the array.

const arr = ['a', 'b', 'c'];
const iterator = arr.keys();
console.log(iterator.next().value); // 0
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2

Similarly, Array.prototype.entries()the method returns an iterator containing the key/value pairs for each element in the array.

const arr = ['a', 'b', 'c'];
const iterator = arr.entries();
console.log(iterator.next().value); // [0, 'a']
console.log(iterator.next().value); // [1, 'b']
console.log(iterator.next().value); // [2, 'c']

Array.prototype.values()Returns an iterator containing the value of each element in the array.

const arr = ['a', 'b', 'c'];
const iterator = arr.values();
console.log(iterator.next().value); // 'a'
console.log(iterator.next().value); // 'b'
console.log(iterator.next().value); // 'c'

10. Array.prototype.reduceRight()

Array.prototype.reduceRight()Methods are very similar to reduce()methods, but the order of traversal is from back to front.

const arr = ['a', 'b', 'c'];
const result = arr.reduceRight((prev, cur) => prev + cur);
console.log(result); // 'cba'

11. Array.prototype.sort()

Array.prototype.sort()Method is used to sort an array, a function can be passed to sort based on some benchmark. Prior to ES6, sorting was done from left to right, which may affect the results of the sort. In ES6, Array.prototype.sort()methods default to using a stable sorting algorithm and Unicodesorting in character order.

const arr = [1,4,3,8,5,2];
arr.sort((a,b) => a-b);
console.log(arr); // [1, 2, 3, 4, 5, 8]

12. Array.prototype.includes()

Array.prototype.includes()The method is used to determine whether an array contains an element, and returns if it does true, otherwise it returns false. Unlike Array.prototype.indexOf()methods, includes()methods support checking NaNfor the existence of .

For example, to determine [1, 2, 3]whether the array contains elements 2and 4, you can use the following method:

const arr = [1, 2, 3];
console.log(arr.includes(2)); // true
console.log(arr.includes(4)); // false

13. Array.prototype.findIndex()

Array.prototype.findIndex()The method returns the index of the first element in the array that matches the condition, or if there is no element that matches the condition -1.

For example, to find the index of [1, 2, 3, 4, 5]the first 3element in the array that is greater than , you can use the following method:

const arr = [1, 2, 3, 4, 5];
const index = arr.findIndex(item => item > 3);
console.log(index); // 3

14. Array destructuring syntax (Array destructuring)

Array destructuring syntax was introduced in ES6, allowing you to quickly access and use the elements of an array by assigning them to variables.

For example, to [1, 2, 3]assign the elements in the array to variables x, yand respectively z, you can use the following method:

const [x, y, z] = [1, 2, 3];
console.log(x); // 1
console.log(y); // 2
console.log(z); // 3

Based on this, we can also use the spread operator to get the remaining elements in the array:

const [x, ...rest] = [1, 2, 3];
console.log(x);        // 1
console.log(rest);     // [2, 3]

15. The difference between Array.from() and Array.of() methods

Array.from()The and methods in ES6 Array.of()are both used to create new arrays, but they behave slightly differently.

  • Array.of()The method can create a new array instance based on the passed parameters and add the passed parameters as elements to the new array:

    const arr = Array.of(1, 2, 3);
    console.log(arr); // [1, 2, 3]
    
  • Array.from()Methods can convert array-like or iterable objects into array instances. This method also accepts an optional map() function, which can be used to transform each element:

    const arr1 = Array.from('foo');
    console.log(arr1); // ['f', 'o', 'o']
    
    const arr2 = Array.from([1, 2, 3], x => x * 2);
    console.log(arr2); // [2, 4, 6]
    

16. Improvements to push(), pop(), shift() and unshift() methods

// push() 方法示例
const arr1 = [1, 2, 3];
arr1.push(4, 5); // 在数组尾部插入多个元素
console.log(arr1); // [1, 2, 3, 4, 5]

// pop() 方法示例
const arr2 = [1, 2, 3];
const last = arr2.pop(); // 弹出数组末尾元素
console.log(last); // 3
console.log(arr2); // [1, 2]

// shift() 方法示例
const arr3 = [1, 2, 3];
const first = arr3.shift(); // 弹出数组头部元素
console.log(first); // 1
console.log(arr3); // [2, 3]

// unshift() 方法示例
const arr4 = [1, 2, 3];
arr4.unshift(-1, 0); // 在数组头部插入多个元素
console.log(arr4); // [-1, 0, 1, 2, 3]

By passing in multiple parameters, the array method push()can unshift()add multiple elements to the tail or head of the array at one time. Compared with using the push() or unshift() method multiple times, this method is more efficient and concise.

17. Chain calls of map(), reduce() and filter() methods

map()The , reduce()and methods of arrays in ES6 filter()all support chained calls, allowing us to operate arrays more elegantly.

For example, the following code uses the reduce()and filter()method chain calls to multiply all elements greater than 2 in the array:

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

const result = arr.filter(item => item > 2)
                 .reduce((prev, curr) => prev * curr, 1);

console.log(result); // 12

In the above code, we first use filter()the method to filter out elements greater than 2, and then reduce()multiply these elements using the method, and finally get the result 12. Chained calls will reduce unnecessary intermediate variables, making the code more concise and efficient.

18. Array.prototype[@@species]

There is a new attribute in ES6 for creating derived classes @@species, which is a function object used to create the constructor of derived classes. In a derived class, if Symbol.speciesthe property is overridden, it will use the overridden @@speciesproperty to create a new instance.

In the following sample code, we define a derived MyArrayclass named, which inherits from the Array class, and overrides Symbol.speciesthe attribute:

class MyArray extends Array {
    
    
  static get [Symbol.species]() {
    
     return Array; }
}

const arr1 = new MyArray(1, 2, 3);

const arr2 = arr1.map(x => x * x);

console.log(arr1 instanceof MyArray); // true
console.log(arr2 instanceof MyArray); // false
console.log(arr2 instanceof Array); // true

In the above code, MyArraythe class overrides Symbol.speciesthe property and returns it Array, so map()the new array instance returned after calling the method is of Array type, not MyArray type.

Summarize

The array API in ES6 has brought many changes, making us more efficient in operating arrays and making the code more concise. In the daily development process, you can make more use of these APIs to improve code work efficiency and development quality.

Guess you like

Origin blog.csdn.net/weixin_55846296/article/details/131211522