ReasonJun

javascript : Array methods that mutate the original array 본문

Frontend/Javasciprt

javascript : Array methods that mutate the original array

ReasonJun 2023. 6. 8. 17:11
728x90

In JavaScript, there are several array methods that can mutate the original array, meaning they modify the array directly instead of creating a new array. These methods allow you to add, remove, or modify elements within an array. Here are some commonly used array methods that have mutating behavior:

 

1. push: The push() method adds one or more elements to the end of an array and returns the new length of the array.

const array = [1, 2, 3];
array.push(4);
console.log(array); // Output: [1, 2, 3, 4]

2. pop: The pop() method removes the last element from an array and returns that element.

const array = [1, 2, 3];
const removedElement = array.pop();
console.log(array); // Output: [1, 2]
console.log(removedElement); // Output: 3

3. shift: The shift() method removes the first element from an array and returns that element. It also updates the indices of the remaining elements.

const array = [1, 2, 3];
const shiftedElement = array.shift();
console.log(array); // Output: [2, 3]
console.log(shiftedElement); // Output: 1

4. unshift: The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

const array = [1, 2, 3];
array.unshift(0);
console.log(array); // Output: [0, 1, 2, 3]

5. splice: The splice() method can be used to add, remove, or replace elements in an array. It modifies the array in place and returns an array containing the removed elements, if any.

const array = [1, 2, 3, 4, 5];
const removedElements = array.splice(2, 2, 6, 7);
console.log(array); // Output: [1, 2, 6, 7, 5]
console.log(removedElements); // Output: [3, 4]

6. sort: The sort() method sorts the elements of an array in place and returns the sorted array. It converts the elements to strings and compares their sequences of UTF-16 code units.

const array = [3, 1, 2];
array.sort();
console.log(array); // Output: [1, 2, 3]

7. reverse: The reverse() method reverses the order of the elements in an array in place.

const array = [1, 2, 3];
array.reverse();
console.log(array); // Output: [3, 2, 1]

8. fill: The fill() method changes all elements in an array to a static value, starting from a specified index and ending at a specified index (optional). It modifies the original array and returns the modified array.

const array = [1, 2, 3, 4, 5];
array.fill(0, 1, 3);
console.log(array); // Output: [1, 0, 0, 4, 5]

9. copyWithin: The copyWithin() method shallow copies part of an array to another location within the same array, overwriting the existing elements. It modifies the original array and returns the modified array.

const array = [1, 2, 3, 4, 5];
array.copyWithin(0, 3);
console.log(array); // Output: [4, 5, 3, 4, 5]
728x90
Comments