简体   繁体   中英

Why does the saved array change its value?

I have the following setup

code

array1 = [['2001-05-01', 20], ['2001-05-02', 23], ['2001-05-03', 18]];

save_ar = array1;
plotarrays2 = [array1];
plotarrays2.push(new_series2(array1, save_ar, 0, 1, 0.1));

function new_series2(origin, stated, start, end, factor) {
    var result = [[]];
    console.log("before " + stated[0][1]);
    result = stated.map(function (item, index) {
        if (index < start || index >= end) return [item[0], 0];
        else return [item[0], item[1] * factor];
    })
    console.log("after " + stated[0][1]);
    for (var i = 0; i < result.length; i++) {
        origin[i][1] = parseInt(origin[i][1]) - result[i][1];
        console.log("after2 " + stated[0][1]); // why????
    }
return result;
};

problem

I expect that after2 should have the same value as before and after. But somehow the stated array is manipulated too. I tried to save it before but it does change anyway.

jsfiddle

http://jsfiddle.net/gcollect/amsn3/

You only made save_ar refer to the array named by array1 . What you want to do is make a copy of the array and its contents. Use:

save_ar = array1.map(function (item) {
    return item.slice(0);
});

instead of:

save_ar = array1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM