0

I am creating a Chrome extension and am getting some weird results with sorted arrays. I have two global arrays called "timearray" and "timearrayorig" (timearray is the sorted version of timearrayorig). In a function, I set a bunch of values in timearrayorig and then copy the entire array to timearray and sort timearray. For some reason, this also sorts timearrayorig. I would greatly appreciate it if someone could explain why this is the case.

for (var i = 0; i < triparray.length; i++) {
    for (var j = 0; j < trainsfeed.length; j++) {
        if (trainsfeed[j].getElementsByTagName('Trip')[0].childNodes[0].nodeValue == triparray[i]) {
            if (timearrayorig.length < i + 1 || timearrayorig[i] > Number(trainsfeed[j].getElementsByTagName('Scheduled')[0].childNodes[0].nodeValue)) {
                timearrayorig.push(Number(trainsfeed[j].getElementsByTagName('Scheduled')[0].childNodes[0].nodeValue));
            }
        }
    }
}
timearray = timearrayorig;
//timearray.sort();

(trainsfeed is a bunch of XML separated by messages and triparray is the list of all the different values for the "Trip" field. timearrayorig and timearray are the earliest times for each element of triparray from the elements of trainsfeed.)

If I run this script and find the value of timearrayorig and timearray in the debug console, they are the same, for example [1365801720, 1365801180, 1365801600, 1365802800, 1365800940]. But when I sort timearray, they both become [1365800940, 1365801180, 1365801600, 1365801720, 1365802800].

4

2 回答 2

1
timearray = timearrayorig;

这不会复制数组;它创建了第二个变量,它引用了同一个数组。仍然只有一个数组,这就是为什么对它进行排序会影响两个变量。要复制数组,请执行以下操作:

var timearray = timearrayorig.slice();

有关详细信息,请参阅:在 JavaScript 中按值复制数组

于 2013-04-12T21:19:44.070 回答
0

timearrayorig持有对数组的引用,因此当您分配timearray = timearrayorig;两个标签时,引用相同的内存空间。

如果要复制数组,可以执行以下操作:

timearray = [];
for(var i = 0; i < timearrayorig.length; i++) timerray[i] = timearrayorig[i];
于 2013-04-12T21:20:43.547 回答