Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function myFunction(someArray)
- {
- // any function that makes an array based on a passed array;
- // someArray has two dimensions;
- // I've tried copying the passed array to a new array like this (I've also used 'someArray' directly in the code);
- funcArray = new Array();
- funcArray = someArray;
- var i = 0;
- for(i=0; i<funcArray.length; i++)
- {
- funcArray[i].reverse;
- }
- return funcArray;
- }
- myArray = [["A","B","C"],["D","E","F"],["G","H","I"]];
- anotherArray = new Array();
- anotherArray = myFunction(myArray);
- // myArray gets modified!;
- anotherArray = myFunction(myArray.valueOf());
- // myArray gets modified!;
- funcArray = new Array();
- funcArray = someArray;
- var funcArray = someArray.slice(0);
- // Use the JSON parse to clone the data.
- function cloneData(data) {
- // Convert the data into a string first
- var jsonString = JSON.stringify(data);
- // Parse the string to create a new instance of the data
- return JSON.parse(jsonString);
- }
- // An array with data
- var original = [1, 2, 3, 4];
- function mutate(data) {
- // This function changes a value in the array
- data[2] = 4;
- }
- // Mutate clone
- mutate(cloneData(original));
- // Mutate original
- mutate(original);
- var arrayWithObjects = [ { id: 1 }, { id: 2 }, { id: 3 } ];
- function mutate(data) {
- // In this case a property of an object is changed!
- data[1].id = 4;
- }
- // Mutates a (DEEP) cloned version of the array
- mutate(cloneData(arrayWithObjects));
- console.log(arrayWithObjects[1].id) // ==> 2
- MY_NEW_OBJECT = JSON.parse(JSON.stringify(MY_OBJECT));
- var aArray = [0.0, 1.0, 2.0];
- var aArrayCopy = new Array(aArray);
- aArrayCopy[0] = "A changed value.";
- console.log("aArrayCopy[0]: "+aArrayCopy[0]+"naArray[0]: "+aArray[0]);
- aArrayCopy[0]: A changed value.
- aArray[0]: 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement