2 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
for (let i = arrayTemp.length; i > 0; i--) {
當(dāng)您在循環(huán)后插入最后一個(gè)元素時(shí),您的循環(huán)次數(shù)太多了。
for (let i = arrayTemp.length - 1; i > 0; i--) {
一種更具邏輯性和可讀性的方式可能是:
while (arrayTemp.length > 1) { // your logic here }

TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個(gè)贊
您在外循環(huán)中循環(huán)所有項(xiàng)目,并且也取消移動最后一個(gè)項(xiàng)目。
const
testFunc = function() {
// Clear the main array and prepare to rebuild it in order
arrayMain = [];
let arrayTemp = arrayBase.slice(0)
// Length of the array times, find the element with smallest number
// in position 1 and move it over to arrayMain.
// This is supposed to ignore the last element since that one does not
// require calculations
for (let i = arrayTemp.length; i > 0; i--) {
let min = arrayTemp[arrayTemp.length - 1][1],
transfer = arrayTemp.length - 1;
for (let x = arrayTemp.length - 2; x >= 0; x--) {
if (arrayTemp[x][1] >= min) {
min = arrayTemp[x][1];
transfer = x;
}
}
arrayMain.unshift(arrayTemp[transfer])
arrayTemp.splice(transfer, 1)
}
// Move over the last array element and log the results
// arrayMain.unshift(arrayTemp[0])
console.log(arrayMain);
};
var arrayMain = [["a", 15, "c"], ["a", 18, "c"], ["a", 11, "c"], ["a", 15, "c"], ["a", 25, "c"]]
var arrayBase = arrayMain.slice(0)
testFunc();
.as-console-wrapper { max-height: 100% !important; top: 0; }
length - 1為了解決這個(gè)問題,您需要使用和 take作為索引來調(diào)整起始值,i而不是使用length.
const
testFunc = function() {
let arrayMain = [];
let arrayTemp = arrayBase.slice(0),
i = arrayTemp.length;
while (--i) {
let min = arrayTemp[i][1],
transfer = arrayTemp.length - 1,
x = i;
while (x--) {
if (arrayTemp[x][1] >= min) {
min = arrayTemp[x][1];
transfer = x;
}
}
arrayMain.unshift(arrayTemp[transfer])
arrayTemp.splice(transfer, 1)
}
arrayMain.unshift(arrayTemp[0])
console.log(arrayMain);
};
var arrayMain = [["a", 15, "c"], ["a", 18, "c"], ["a", 11, "c"], ["a", 15, "c"], ["a", 25, "c"]]
var arrayBase = arrayMain.slice(0)
testFunc();
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
舉報(bào)