排序后如何访问最初传递的数组?

问题描述 投票:-1回答:4

将数组[2,1,3,5,3,2,1]传递给此函数时,我选择从最小到最大排序。但是,当我尝试记录或使用原始数组时,“sorted”和“a”都记录相同的排序数组。我不确定为什么排序超出了“已排序”变量的范围。

function firstDuplicate(a) {
    let sorted = a.sort((a,b) => a - b);
    let duplicates = [];
    let indexes = [];

    console.log(sorted);
    console.log(a);

有任何想法吗?谢谢!

javascript arrays sorting ecmascript-6
4个回答
1
投票

sort对数组进行排序 - 它不复制数组并创建一个新数组,原始数组被修改。如果要分离原始文件和已排序文件,则应在排序之前先明确复制,这可以通过在原始文件上调用slice(0)来完成:

function firstDuplicate(a) {
  let sorted = a.slice(0).sort((a, b) => a - b);
  let duplicates = [];
  let indexes = [];

  console.log(sorted);
  console.log(a);
}
firstDuplicate([2, 1, 3, 5, 3, 2, 1])

1
投票

sort破坏性地对数组进行排序并返回它。没有更多“未排序”的数组。如果以后需要未排序的数组,请在排序之前克隆它:

let unsorted = Array.from(a)
a.sort(...)

(编辑:你是否对克隆进行排序,如评论中的Jaromanda X,或者像我这样的原始文件,只要你从两个数组开始,这并不重要。)


0
投票

在Javascript数组中进行了排序,这就是为什么更改反映在两个数组中的原因。你可以做的是克隆原始数组,然后对克隆的数组进行排序。您可以使用'Array.slice()'克隆数组,(Array.slice()返回一个新数组)。

   let sorted = a.slice().sort();

-1
投票

你需要从原始数组创建一个副本,试试这个

Array.prototype.clone = function(){
        let array = this;
        let newArray = [];
        // clone the objects in array
        let cloneObject = function(item){
            let newObject = {};
            for(o in item){
                if(typeof(item[o])!="object"){
                    newObject[o] = item[o];   
                }
                else{
                    newObject[o] = cloneObject(item[o]);   
                }
            }                
         return newObject;

        }
        for(let i =0; i<array.length;i++){
            let item = array[i];
            // if item is not object add value to array
            if(typeof(item)!="object"){
                newArray.push(item);
            }
            // if element is object, clone item and add to array
            else{
                newArray.push(cloneObject(item));
            }
        }
        return newArray;

    }

        function firstDuplicate(a) {
                let sorted = a.clone().sort((a, b) => a - b);
                let duplicates = [];
                let indexes = [];

                console.log(sorted);
                console.log(a);
        }
        var element = [2, 1, 3, 5, 3, 2, 1];
        firstDuplicate(element)
© www.soinside.com 2019 - 2024. All rights reserved.