Home >Web Front-end >JS Tutorial >The difference between slice and splice in js

The difference between slice and splice in js

下次还敢
下次还敢Original
2024-05-01 04:09:15471browse

The difference between slice and splice in JavaScript is as follows: slice() returns a new copy of the array and does not change the original array; splice() modifies the original array. The syntax of slice() is slice(start, end), and the syntax of splice() is splice(start, deleteCount, ...items). slice() copies elements starting at a specified position, and splice() removes or replaces elements starting at a specified position.

The difference between slice and splice in js

The difference between slice and splice in JS

Get straight to the point

slice() and splice() are two methods used to manipulate arrays in JavaScript, but their functions are different.

Detailed expansion

slice()

  • Returns a shallow copy of the array (new array).
  • The original array will not be modified.
  • Syntax: slice(start[, end])
  • Parameters:

    • start: Required, start copying elements from this index.
    • end: Optional, copy to this index (exclusive).

Example:

<code class="js">const arr = [1, 2, 3, 4, 5];
const newArr = arr.slice(2); // [3, 4, 5]</code>

splice()

  • From array Removes or replaces an element and returns the removed element.
  • will modify the original array.
  • Syntax: splice(start, deleteCount[, ...items])
  • Parameters:

    • ## start: Required, start removing elements from this index.
    • deleteCount: Required, the number of elements to be removed.
    • ...items: Optional, the element to be inserted at index start, if specified.

Example:

<code class="js">const arr = [1, 2, 3, 4, 5];
arr.splice(2, 2, 10, 11); // [1, 2, 10, 11, 5]</code>

Summary

  • slice () Returns a shallow copy of the array without modifying the original array.
  • splice() Removing or replacing elements from an array modifies the original array.

The above is the detailed content of The difference between slice and splice in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use splice in jsNext article:How to use splice in js