排序javascript数组foreach

时间:2017-12-23 07:09:32

标签: javascript arrays sorting foreach integer

我是编程新手。有人可以解释这个函数如何排序整数数组?它似乎是对数组进行排序。在这里创建数组“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])

1 个答案:

答案 0 :(得分:4)

数组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])

当然,有一种更好的方法可以使用内置sort函数对数组进行排序。

[3, 4, 1, 2, -3, 20, 10, 22, 7, 5, 7, 8, 200, 6].sort(function(a,b){
  return a-b  
})