33

JavaScript Splice Tutorial

 5 years ago
source link: https://www.tuicool.com/articles/hit/QzQJBfE
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript’s splice is a function that is used to insert, remove and replace items in an array. You use it by choosing a position in the array to work with, choosing how many items to delete, and the new items (if any) to insert at the same time. As a bonus, it also returns the removed items in-case that is useful to you.

The arguments to splice are as follows:

  • index - the index within the array to work at.
  • howmany - the number of items to remove.
  • items - zero, one or more items to insert at the index position once the items are deleted.

Beware that splice changes the original array. Not all Javascript array functions do this, but splice does. This has the advantage of making splice fast because it doesn’t need to copy the whole array, but it does mean you need to think about what other parts of your program might be using the same array and if you will affect them.

Here is an example where we only remove items:

var beatles = ["John", "Paul", "Brian", "Keith", "Mick", "Bill", "Charlie", "Ian", "George", "Ringo"];
var stones = beatles.splice(2, 6);
console.log(beatles);
console.log(stones);

// Results:
//
// ["John", "Paul", "George", "Ringo"]
// ["Brian", "Keith", "Mick", "Bill", "Charlie", "Ian"]

Here is an example where we only add items:

var shopping = ["Milk", "Bread", "Bananas", "Juice"];
shopping.splice(0, 0, "Coffee", "Rosemary");
console.log(shopping);

// Result:
//
// ["Coffee", "Rosemary", "Milk", "Bread", "Bananas", "Juice"]

Here is an example where we remove and add items at the same time:

var fib = [0, 1, 1, 2, 0, 0, 0, 13, 21, 34, 55];
fib.splice(4, 3, 3, 5, 8);
console.log(fib);

// Result:
//
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Javascript splice on strings

Can you use JavaScript’s splice on a string? The answer is that Javascript doesn’t allow this, but it is easy to create your own function to do it. Here are two ways you can do it taken from this StackOverflow answer :

Fast way to splice strings:

function spliceString(str, index, count, add) {
  // We cannot pass negative indexes directly to the 2nd slicing operation.
  if (index < 0) {
    index = str.length + index;
    if (index < 0) {
      index = 0;
    }
  }

  return str.slice(0, index) + (add || "") + str.slice(index + count);
}

Intuitive but slower way to splice strings:

function spliceString(str, index, count, add) {
  var ar = str.split('');
  ar.splice(index, count, add);
  return ar.join('');
}

These functions don’t work exactly like their array equivalents. Can you spot the difference?

The difference is that these functions don’t alter the original string, but create a new one and return that. This is because strings are immutable in Javascript. In other words, strings cannot be changed. All functions that work with strings and need to change them will create a new string with the changed text.

Summary

Javascript splice is an array manipulation tool that can add and remove multiple items from an array. It works on the original array rather than create a copy. It ‘mutates’ the array. It doesn’t work with strings but you can write your own functions to do that quite easily.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK