Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. var s = ["hi"];
  2. console.log(s);
  3. s[0] = "bye";
  4. console.log(s);
  5.  
  6. ["hi"]
  7. ["bye"]
  8.  
  9. ["bye"]
  10. ["bye"]
  11.  
  12. var s = ["hi"];
  13. console.log(s.toString());
  14. s[0] = "bye";
  15. console.log(s.toString());
  16.  
  17. hi
  18. bye
  19.  
  20. 1. arr.toString() // not well for [1,[2,3]] as it shows 1,2,3
  21. 2. arr.join() // same as above
  22. 3. arr.slice(0) // a new array is created, but if arr is [1, 2, arr2, 3]
  23. // and arr2 changes, then later value might be shown
  24. 4. arr.concat() // a new array is created, but same issue as slice(0)
  25. 5. JSON.stringify(arr) // works well as it takes a snapshot of the whole array
  26. // or object, and the format shows the exact structure
  27.  
  28. console.log(s); // ["bye"], i.e. incorrect
  29. console.log(s.slice()); // ["hi"], i.e. correct
  30.  
  31. console.logShallowCopy = function () {
  32. function slicedIfArray(arg) {
  33. return Array.isArray(arg) ? arg.slice() : arg;
  34. }
  35.  
  36. var argsSnapshot = Array.prototype.map.call(arguments, slicedIfArray);
  37. return console.log.apply(console, argsSnapshot);
  38. };
  39.  
  40. console.logSanitizedCopy = function () {
  41. var args = Array.prototype.slice.call(arguments);
  42. var sanitizedArgs = JSON.parse(JSON.stringify(args));
  43.  
  44. return console.log.apply(console, sanitizedArgs);
  45. };
  46.  
  47. console.log(JSON.stringify(the_array));
  48.  
  49. var s = ["hi"];
  50. console.log(CloneArray(s));
  51. s[0] = "bye";
  52. console.log(CloneArray(s));
  53.  
  54. function CloneArray(array)
  55. {
  56. var clone = new Array();
  57. for (var i = 0; i < array.length; i++)
  58. clone[clone.length] = array[i];
  59. return clone;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement