2 回答
TA贡献1828条经验 获得超13个赞
for (let i = arrayTemp.length; i > 0; i--) {
当您在循环后插入最后一个元素时,您的循环次数太多了。
for (let i = arrayTemp.length - 1; i > 0; i--) {
一种更具逻辑性和可读性的方式可能是:
while (arrayTemp.length > 1) { // your logic here }
TA贡献1843条经验 获得超7个赞
您在外循环中循环所有项目,并且也取消移动最后一个项目。
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为了解决这个问题,您需要使用和 take作为索引来调整起始值,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; }
添加回答
举报