Austin Story

Ruby, Rails and Javascript Blog

Powered by Genesis

Using Splice to copy objects in javascript.

December 24, 2015 By Austin Story Leave a Comment

Splice will copy an array from one point to another. It uses a shallow copy to replicate the array. That means it will copy literals exactly, but will copies objects by reference.

Examples of literals. Note that changing the original after the splice() does not change the copy

[code]
original = [1,2,3]
copy = original .splice()

original [0] = 5

original => [5,2,3]
copy => [1,2,3]
[/code]

But objects are by reference. Note that when we change the name of the object in the original, the copy is also changed.

[code]
person = {name: ‘Jimbo’}

original = [1,2,3, person]
copy = original.splice()

original[0].name = ‘Bill’

original[4].name => ‘Bill’
copy[4].name => ‘Bill’

[/code]

Filed Under: Javascript, Programming Tagged With: copy, Javascript, splice

Categories

  • AngularJS
  • Books
  • Devise
  • Elasticsearch
  • ES6
  • Information Security
  • Integrations
  • Javascript
  • Linux
  • Minitest
  • PhoneGap
  • Programming
  • React
  • Redux
  • Ruby
  • Ruby on Rails
  • Stripe
  • Testing
  • Theory
  • TypeScript
  • Uncategorized
  • Vue
  • Webpack