0

I need to make a temporary copy of a variable to make changes to. Here's what I mean:

var x = ["a", "b", "c"];
var y = x;
y[1] = "2"
//x: ["a", "b", "c"];
//y: ["a", 2, "c"];

It's worth pointing out that I'm using an object I defined myself, and not a built in data structure.

Captain Stack
  • 3,572
  • 5
  • 31
  • 56

3 Answers3

1

The standard method for 'cloning' array of primitive types in JavaScript (based on your requirements) is shown below:

var x = ["a", "b", "c"];
var y =  x.slice(0);
y[1] = "2";

Be aware, that if array contains complex types (objects), then it will keep original references; in other words, it does not perform 'deep' copy on array of objects.

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
0

Try this

var x = ["a", "b", "c"];
var y = JSON.parse(JSON.stringify(x));
//y = ["a", "b", "c"];

Then u can manipulate your new object as u want.

lintu
  • 1,092
  • 11
  • 24
0

You can use jQuery to clone your object

var newObject = jQuery.extend(true, {}, oldObject);

jQuery Documentation

Prat
  • 495
  • 7
  • 19