我是编程的新手。有人可以解释一下此函数如何分类整数数组吗?它似乎正在对数组进行排序。在这里创建数组" D"的目的是什么?
function asc(f) {
var d = [];
f.map(function(e, i, a) {
d[i] = e
})
var k = [];
f.forEach(function(e, i, a) {
var g = d.indexOf(Math.min.apply(null, d))
var s = d.splice(g, 1)
k[i] = s
})
document.write(k)
}
asc([3, 4, 1, 2, -3, 20, 10, 22, 7, 5, 7, 8, 200, 6])
数组d
是原始数组的精确副本。该代码使用此副本,因为故意删除了每个itteration上的最小元素,并将其存储在新的k
数组中,这是最终排序的数组。我已经在代码中发表了评论,向您展示了每行的作用。
function asc(f) {
//f is the original array
var d = [];
f.map(function(e, i, a) {
d[i] = e
})// create d as an exact copy of f
var k = []; // the final sorted array
f.forEach(function(e, i, a) {
var g = d.indexOf(Math.min.apply(null, d)) // get the position of the minimum element of d
var s = d.splice(g, 1) // remove the minimum element from d and store it in s
k[i] = s // put s in the k array
})
document.write(k) // write the sorted array in document
}
asc([3, 4, 1, 2, -3, 20, 10, 22, 7, 5, 7, 8, 200, 6])
当然有一种更好的方法可以使用内置排序函数对数组进行分类。
[3, 4, 1, 2, -3, 20, 10, 22, 7, 5, 7, 8, 200, 6].sort(function(a,b){
return a-b
})