因此,我一直在为学校内的一家商店制作一个网站,以获得一些经验,也许以后会成为一名网络开发人员。网站后端编程比我预想的要有趣得多,直到我遇到这个问题,我已经调试了几个小时,但进展甚微。
我用一个稍微简单的函数重新创建了这种情况。请允许我解释一下一切的目的:
arrayMain
:我要排序的数组。它包含更多我希望按 1 位置中的数字排序的数组。
arrayBase
:该副本的arrayMain
目的是永远不会被编辑。如果需要,主要用于“取消排序” arrayMain
。
arrayTemp
:它的副本arrayBase
用于选择排序。重复地将编号最小的项目移回arrayMain
。
min
和transfer
:要移动 1 个数组元素,则arrayTemp
扫描整个数组。min
从列表中最后一项的数字开始。如果检测到新的最小值,则将其设置为transfer
。当检查完所有项目后,arrayTemp[transfer]
被移入arrayMain
。
var arrayMain = [["a", 15, "c"], ["a", 18, "c"], ["a", 11, "c"] ,["a", 15, "c"], ["a", 25, "c"]]
var arrayBase = arrayMain.slice(0)
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)
}
testFunc()
预期结果:
[ ["a", 11, "c"], ["a", 15, "c"], ["a", 15, "c"], ["a", 18, "c"], ["a", 25, "c"] ]
实际结果:
[ undefined, ["a", 11, "c"], ["a", 15, "c"], ["a", 15, "c"], ["a", 18, "c"], ["a", 25, "c"] ]
我知道删除它很容易arrayMain[0]
,但我想知道是否有一种方法可以阻止这个未定义的元素首先出现,或者至少知道是什么造成了它。
或者,如果你有自己的排序方式,不仅有效而且速度更快,我想我也会接受这一点,但我真的想知道它来自哪里,因为undefined
如果我从来没有弄清楚我将来可能会再次陷入这种境地。
慕田峪7331174
蓝山帝景
相关分类