如果我有一个数组列表并用以下方法对其进行排序:
myArrayList.sort(function(a, b) { return a - b });
是否可以在不备份未排序数组的情况下将“myArrayList”恢复到 .sort 发生之前的顺序?可以这么说,撤消排序。
最佳答案
是的,使用之前制作的副本 Array#slice()
就像这样,排序之前。
The
slice()
method returns a shallow copy of a portion of an array into a new array object.
var myArrayListCopy = myArrayList.slice();
var myArrayList = [1000, 5, 2, 8, 42, 101, 111, 20],
myArrayListCopy = myArrayList.slice(); // make copy from unsorted array first
document.write('<pre>original ' + JSON.stringify(myArrayList, 0, 4) + '</pre>');
myArrayList.sort(function (a, b) { return a - b; });
document.write('<pre>sorted ' + JSON.stringify(myArrayList, 0, 4) + '</pre>');
myArrayList = myArrayListCopy; // assign backup
document.write('<pre>from backup ' + JSON.stringify(myArrayList, 0, 4) + '</pre>');
关于javascript - “unsorting”数组 - 让数组恢复到 .sort javascript 之前的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36151163/