[英]Insertion sort on an array of objects with javascript
我有這個數組,其中的對象看起來像這樣
{
n: 15,
color: "red"
}
我正在嘗試使用以下 function 對其進行排序
async insertionSort() {
let len = this.array.length;
let value;
let i;
let j;
//let current;
// let arr = this.array;
for (i = 0; i < len; i++) {
value = this.array[i].n;
//current = this.array[i];
for (j = i - 1; j > -1 && this.array[j].n > value; j++) {
//arr[j + 1] = arr[j];
// HF.arraySwap(this.array, this.array[j + 1], this.array[j]);
this.array[j + 1] = this.array[j];
}
// arr[j + 1] = value;
HF.arraySwap(this.array, this.array[j + 1], this.array[i]);
await HF.sleep();
}
}
** 我不能使用 array.sort(...) 因為我正在嘗試對算法進行可視化,我正在使用對象來更改我在屏幕上呈現的條形的顏色 **當我點擊第二個for循環我得到一個錯誤“無法讀取未定義的屬性'n'”,當我只用數字運行它時它工作正常但是當我用對象嘗試它時它給出了錯誤。我現在知道我用完了數組,有沒有辦法可以克服這個問題並且仍然對對象數組進行排序? 另外,我正在使用 VueJS 來顯示所有這些
在第一次迭代i=0
時,您以值為 -1 j=i-1
開始第二個循環。 數組不包含索引為 -1 的項目: array[-1]
is undefined
。 只要 JavaScript 可以比較不同類型的變量,它就可以與數字一起使用,因為數字和未定義的比較不會觸發錯誤
順便說一句,您可以使用Array.proototype.sort方法,它看起來像:
console.log(myArr.sort((a,b) => an - bn))
<script> const myArr = [ { n: 1, color: "red" }, { n: 44, color: "orange" }, { n: 13, color: "yellow" }, { n: 8, color: "green" }, { n: 2, color: "blue" } ]; </script>
試試 this.array[i].n 寫 this.array[i][n] 和 this.array[j].n 寫 this.array[j][n]
有什么理由不使用這樣的排序方法嗎?:
const arr = [
{ n: 10, color: "red" },
{ n: 20, color: "yellow" },
{ n: 15, color: "black" },
{ n: 7, color: "white" },
{ n: 23, color: "blue" }
];
const ascSorted = arr.sort((a, b) => a.n - b.n);
const descSorted = arr.sort((a, b) => b.n - a.n);
console.log(ascSorted);
// [
// { n: 7, color: "white" },
// { n: 10, color: "red" },
// { n: 15, color: "black" },
// { n: 20, color: "yellow" },
// { n: 23, color: "blue" }
// ];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.