Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var s = ["hi"];
- console.log(s);
- s[0] = "bye";
- console.log(s);
- ["hi"]
- ["bye"]
- ["bye"]
- ["bye"]
- var s = ["hi"];
- console.log(s.toString());
- s[0] = "bye";
- console.log(s.toString());
- hi
- bye
- 1. arr.toString() // not well for [1,[2,3]] as it shows 1,2,3
- 2. arr.join() // same as above
- 3. arr.slice(0) // a new array is created, but if arr is [1, 2, arr2, 3]
- // and arr2 changes, then later value might be shown
- 4. arr.concat() // a new array is created, but same issue as slice(0)
- 5. JSON.stringify(arr) // works well as it takes a snapshot of the whole array
- // or object, and the format shows the exact structure
- console.log(s); // ["bye"], i.e. incorrect
- console.log(s.slice()); // ["hi"], i.e. correct
- console.logShallowCopy = function () {
- function slicedIfArray(arg) {
- return Array.isArray(arg) ? arg.slice() : arg;
- }
- var argsSnapshot = Array.prototype.map.call(arguments, slicedIfArray);
- return console.log.apply(console, argsSnapshot);
- };
- console.logSanitizedCopy = function () {
- var args = Array.prototype.slice.call(arguments);
- var sanitizedArgs = JSON.parse(JSON.stringify(args));
- return console.log.apply(console, sanitizedArgs);
- };
- console.log(JSON.stringify(the_array));
- var s = ["hi"];
- console.log(CloneArray(s));
- s[0] = "bye";
- console.log(CloneArray(s));
- function CloneArray(array)
- {
- var clone = new Array();
- for (var i = 0; i < array.length; i++)
- clone[clone.length] = array[i];
- return clone;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement