Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. function myFunction(someArray)
  2. {
  3. // any function that makes an array based on a passed array;
  4. // someArray has two dimensions;
  5. // I've tried copying the passed array to a new array like this (I've also used 'someArray' directly in the code);
  6.  
  7. funcArray = new Array();
  8. funcArray = someArray;
  9.  
  10. var i = 0;
  11.  
  12. for(i=0; i<funcArray.length; i++)
  13. {
  14. funcArray[i].reverse;
  15. }
  16.  
  17. return funcArray;
  18.  
  19. }
  20.  
  21. myArray = [["A","B","C"],["D","E","F"],["G","H","I"]];
  22. anotherArray = new Array();
  23.  
  24. anotherArray = myFunction(myArray);
  25. // myArray gets modified!;
  26.  
  27. anotherArray = myFunction(myArray.valueOf());
  28. // myArray gets modified!;
  29.  
  30. funcArray = new Array();
  31. funcArray = someArray;
  32.  
  33. var funcArray = someArray.slice(0);
  34.  
  35. // Use the JSON parse to clone the data.
  36. function cloneData(data) {
  37. // Convert the data into a string first
  38. var jsonString = JSON.stringify(data);
  39.  
  40. // Parse the string to create a new instance of the data
  41. return JSON.parse(jsonString);
  42. }
  43.  
  44. // An array with data
  45. var original = [1, 2, 3, 4];
  46.  
  47. function mutate(data) {
  48. // This function changes a value in the array
  49. data[2] = 4;
  50. }
  51.  
  52. // Mutate clone
  53. mutate(cloneData(original));
  54.  
  55. // Mutate original
  56. mutate(original);
  57.  
  58. var arrayWithObjects = [ { id: 1 }, { id: 2 }, { id: 3 } ];
  59.  
  60. function mutate(data) {
  61. // In this case a property of an object is changed!
  62. data[1].id = 4;
  63. }
  64.  
  65. // Mutates a (DEEP) cloned version of the array
  66. mutate(cloneData(arrayWithObjects));
  67.  
  68. console.log(arrayWithObjects[1].id) // ==> 2
  69.  
  70. MY_NEW_OBJECT = JSON.parse(JSON.stringify(MY_OBJECT));
  71.  
  72. var aArray = [0.0, 1.0, 2.0];
  73. var aArrayCopy = new Array(aArray);
  74. aArrayCopy[0] = "A changed value.";
  75. console.log("aArrayCopy[0]: "+aArrayCopy[0]+"naArray[0]: "+aArray[0]);
  76.  
  77. aArrayCopy[0]: A changed value.
  78. aArray[0]: 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement