当前位置: 动力学知识库 > 问答 > 编程问答 >

Array by Reference vs Array by Value in Javascript

问题描述:

I'm reading Data Structures and Algorithms with Javascript by O'reily and it states the following:

Shallow copy (two arrays point to the same location in memory):

var nums = [];

for (var i = 0; i < 100; ++i) {

nums[i] = i+1;

}

var samenums = nums;

nums[0] = 400;

print(samenums[0]); // displays 400

Deep copy:

function copy(arr1, arr2) {

for (var i = 0; i < arr1.length; ++i) {

arr2[i] = arr1[i];

}

}

Now the following code fragment produces the expected result:

var nums = [];

for (var i = 0; i < 100; ++i) {

nums[i] = i+1;

}

var samenums = [];

copy(nums, samenums);

nums[0] = 400;

print(samenums[0]); // displays 1

Why is a function required in order to create deep copies?

网友答案:

As stated in the comments, the function is purely for aesthetics and reusability, and is not strictly necessary.

You could refactor your example:

function copy(arr1, arr2) {
    for (var i = 0; i < arr1.length; ++i) {
        arr2[i] = arr1[i];
    }
}

var nums = [];
for (var i = 0; i < 100; ++i) {
    nums[i] = i+1;
}
var samenums = [];
copy(nums, samenums);
nums[0] = 400;
print(samenums[0]); // displays 1

into this equivalent function-less example:

var nums = [];
for (var i = 0; i < 100; ++i) {
    nums[i] = i+1;
}
var samenums = [];
for (var i = 0; i < nums.length; ++i) {
    samenums[i] = nums[i];
}
nums[0] = 400;
print(samenums[0]); // displays 1
分享给朋友:
您可能感兴趣的文章:
随机阅读: