JavaScript provides a variety of methods to add, remove, and replace elements of an array, but some will affect the original array; some will not, it is a new array.
Note: Distinguish the differences between the following two methods:
array.splice() affects the original array
array.slice() does not affect the original array
I. New: Affect the original array
Adding new elements using array.push() and array.ushift() affects the original array.
II. New: Does not affect the original array
There are two ways to add new elements without affecting the original array. The first is array.concat().
The second way is to use JavaScript's spread operator, which is three dots (…)
The spread operator copies the original array, removes all elements from the original array, and stores them in the new environment.
III. Remove: Affect the original array
When array.pop() and array.shift() are used to remove array elements, the original array is affected.
array.pop() and array.shift() return the removed element, you can get the removed element through a variable
array.splice() can also delete elements of an array
Like array.pop() and array.shift(), array.splice() also returns the removed element
IV. Removal: does not affect the original array
JavaScript's array.filter() method creates a new array based on the original array, the new array only contains elements that match certain criteria
The condition of the above code is "not equal to 'e'", so the new array (arr2) does not contain 'e'.
Uniqueness of arrow functions:
For single-line arrow functions, the 'return' keyword is included by default and does not need to be written manually.
However, multiline arrow functions need to explicitly return a value.
Another way that doesn't affect the original array is array.slice() (not to be confused with array.splice() ).
V. Replacement: affects the original array
If you know which element to replace, you can use array.splice()
VI. Replacement: does not affect the original array
A new array can be created using array.map(), and each element can be inspected, replacing them based on certain conditions.
Transform data using array.map()
array.map() is a powerful method that can be used to transform data without polluting the original data source
Original: http://lorenstewart.me/2017/01/22/javascript-array-methods-mutating-vs-non-mutating/