我是编程新手。有人能解释一下这个函数如何对整数数组进行排序吗?它似乎正在对数组进行排序。这里创建数组“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
是原始数组的精确副本。
该代码使用此副本是因为有意删除每次迭代中的最小元素并将其存储在新的 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])
当然有更好的方法使用内置 sort 对数组进行排序功能。
[3, 4, 1, 2, -3, 20, 10, 22, 7, 5, 7, 8, 200, 6].sort(function(a,b){
return a-b
})
关于javascript - javascript 数组 foreach 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47950558/