简体   繁体   English

排序JavaScript数组foreach

[英]Sorting javascript array foreach

I am new to programming. 我是编程新手。 Can someone explain how is this function sorting integer array? 有人可以解释这个函数如何对整数数组进行排序吗? It appears to be sorting an array. 它似乎正在对数组排序。 What is the purpose of creating array "d" here? 在这里创建数组“ 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]) 

The array d is an exact copy of the original array. 数组d是原始数组的精确副本。 The code uses this copy because intentionally removes the minimum element on each itteration and stores it in the new k array which is the final sorted array. 该代码使用此副本,是因为有意删除了每个发射的最小元素,并将其存储在作为最终排序数组的新k数组中。 I have made comments in the code to show you what each line does. 我在代码中添加了注释,以向您显示每一行的功能。

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

Ofcourse there is a better way to sort an array using the builtin sort function. 当然,有一种使用内置排序功能对数组进行排序的更好方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM