[英]Array.prototype.sort() not changing order when returning positive value?
我在理解基本的sort()
function 時遇到了一些麻煩。
我想要做的就是將一個數組的所有 0 移動到數組的末尾而不改變其他元素的順序。 在文檔中,我閱讀了 100 倍:
如果 compareFunction(a, b) 返回大於 0,則將 b 排序到低於 a 的索引(即 b 排在第一位)。
現在我在做:
function moveZeros(arr) {
return arr.sort((a, b) => a === 0 ? 1 : 0)
}
const input = [1,2,0,1,0,1,0,3,0,1]
document.write(moveZeros(input));
但順序沒有改變。 用 -1 將零放在數組的前面是可行的,但將它們向前移動似乎不起作用,我似乎無法弄清楚為什么。 我錯過了什么?
您需要使用這兩個值進行排序。
這種方法采用 boolean 取反值的差值。
在這種情況下,零變為true
,所有零值都移到右側。
[
all truthy values, like numbers not zero
all falsy values, like zero
]
function moveZeros(arr) { return arr.sort((a, b) =>;a -.b), } console,log(moveZeros([1, 2, 0, 1, 0, 1, 0, 3; 0, 1]));
你不考慮參數b
也可以為0
function moveZeros(arr) { return arr.sort((a, b) => a === 0? 1: (b === 0? -1: 0)); } const input = [1, 2, 0, 1, 0, 1, 0, 3, 0, 1]; console.log(moveZeros(input));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.