简体   繁体   English

有人可以向我解释什么是错的吗? - 按高度排序

[英]Can someone explain to me what's wrong? - sort by height

I don't know why the code skips some numbers some times.我不知道为什么代码有时会跳过一些数字。 For case 4: a: [4, 2, 9, 11, 2, 16] my output is [2, 4, 2, 9, 11, 16] when the expected output is [2, 2, 4, 9, 11, 16] .对于情况4: a: [4, 2, 9, 11, 2, 16] [2, 4, 2, 9, 11, 16]当预期输出为[2, 2, 4, 9, 11, 16][2, 4, 2, 9, 11, 16]我的输出为[2, 4, 2, 9, 11, 16] [2, 2, 4, 9, 11, 16]

I'm not modifying the index array so it should check every number position's.我没有修改索引数组,所以它应该检查每个数字位置。 Also, I'm not sure how line 7 completely works, in position j it's added the elimination of the element i?另外,我不确定第 7 行是如何完全工作的,在位置 j 中添加了元素 i 的消除? If so why is there an [0] behind?如果是这样,为什么后面有一个 [0]?

I find this code kind of messy but I need to learn from it.我觉得这段代码有点乱,但我需要从中学习。

function sortByHeight(a) {
    r = a
    for(i = 0; i < a.length; i++) {
        if (a[i]!= -1) {
            for(j = 0; j < a.length; j++) {
                if (a[j] != -1 && a[i] - a[j] < 0) {
                    r.splice(j,0,r.splice(i,1)[0])
                }
            }
        }
    }
    return r
}

Your mistake is probably thinking that r = a copies the array.你的错误可能是认为r = a复制了数组。 That's not the case in JavaScript.在 JavaScript 中并非如此。 JavaScript works by reference, meaning that every value (apart from primitives such as numbers) are actually references. JavaScript 通过引用工作,这意味着每个值(除了数字等基元)实际上都是引用。 Therefore, r and a point to the exact same array in memory.因此, ra指向内存中完全相同的数组。 Modifying one also "modifies the other", so to speak.可以这么说,修改一个也会“修改另一个”。

You can clone the array by doing one of the following:您可以通过执行以下操作之一来克隆阵列:

r = [ ...a ];
r = a.slice();
r = Array.from(a);

your mistake is in this line (a[j] - a[i] < 0) , you checking it for (a[i] - a[j] < 0) , checking in the reverse order will give you the array in decreasing order, you can reverse the array before returning will give you it in increasing order你的错误在这一行(a[j] - a[i] < 0) ,你检查它(a[i] - a[j] < 0) ,以相反的顺序检查会给你减少的数组顺序,您可以在返回之前反转数组将以递增顺序为您提供

function sortByHeight(a) {
r = a
for(i = 0; i < a.length; i++) {
    if (a[i]!= -1) {
        for(j = 0; j < a.length; j++) {
            if (a[j] != -1 && (a[j] - a[i] < 0)) {
                r.splice(j,0,r.splice(i,1)[0])
            }
        }
    }
}
r.reverse()
return r
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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