Last active
August 29, 2015 14:26
-
-
Save sagiavinash/11de50cb64e8d6a782e4 to your computer and use it in GitHub Desktop.
Copying an Array (Referenced & Non-Referenced/Snapshot)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// generally for in loops are used to save a non-referenced copy/snapshot of an array. this is a far simpler method to acheive the same | |
var arr = [1, 2, 3]; | |
// referenced copy of an array. | |
var arr_ref_copy = arr; | |
// non-referenced copy or snapshot of an array. | |
var arr_snapshot = arr.slice(0); | |
// update original array. | |
arr.push(4); | |
console.log(arr_ref_copy); // returns [1, 2, 3, 4] - referenced copy gets updated. | |
console.log(arr_snapshot); // returns [1, 2, 3] - non-referenced copy/snapshot is unchanged. | |
/** | |
* Note: | |
* If its an array like object like "arguments" of a function use - | |
* var arguments_snapshot = Array.prototype.slice.call(arguments, 0); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment