我有一個陣列,其中一個包含以下值:
墓 = [4, 6, 1, 3, 5, 0, 2]
tomb[0] = 4
tomb[1] = 6
tomb[2] = 1
tomb[3] = 3
tomb[4] = 5
tomb[5] = 0
tomb[6] = 2
請問可以這樣轉換嗎:
tomb[5] = 0
tomb[2] = 1
tomb[6] = 2
tomb[3] = 3
tomb[0] = 4
tomb[4] = 5
tomb[1] = 6
我想在 for 回圈中使用這個陣列值,但在我必須從最小值開始并增加到最大之前。所以我想得到一個從最小值到最大值的陣列索引串列。
const arr = [4, 6, 1, 3, 5, 0, 2];
const min = Math.min.apply(null, arr);
const index = arr.indexOf(min);
console.log(index);
uj5u.com熱心網友回復:
您可以獲取陣列的鍵并按給定陣列的值對索引進行排序。
const
array = [4, 6, 1, 3, 5, 0, 2],
indices = [...array.keys()].sort((a, b) => array[a] - array[b]);
console.log(...indices);
uj5u.com熱心網友回復:
array.sort通過使用和嘗試這個array.indexOf
const arr = [4, 6, 1, 3, 5, 0, 2];
const newarr = arr.slice()
const arrindex = []
newarr.sort()
newarr.forEach(i=>{
arrindex.push(arr.indexOf(i))
})
console.log(arrindex)
uj5u.com熱心網友回復:
只需使用Array.sort()
const arr = [4, 6, 1, 3, 5, 0, 2];
const sorted = arr
.map((value, index) => ({ index, value }))
.sort((a, b) => a.value - b.value)
console.log(
sorted.map(entry => entry.index),
sorted.map(entry => entry.value)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/424724.html
標籤:javascript html 数组 for循环 索引
