-3

所以我读了关于在数组中排序元素的文章。这是一些代码:

 function compareNumeric(a, b) {
   if (a > b) return -1;
   if (a < b) return 1;
 }

 var arr = [ 1, 2, 15 ];

arr.sort(compareNumeric);

 alert(arr);  // 1, 2, 15

我不理解它的逻辑。为什么我们在这种情况下不使用 for() ?

4

2 回答 2

1

.sort() 函数允许回调函数比较数组项。您的回调函数从排序算法中被多次调用。此链接可能对您有所帮助http://www.w3schools.com/jsref/jsref_sort.asp

于 2013-06-06T06:45:53.510 回答
0

http://www.w3schools.com/jsref/jsref_sort.asp

检查此链接... n yaa您仅使用排序功能..所以不需要for循环。并且在 js 中,当您对数字 i/p 使用排序函数时,您必须将函数作为参数来告诉如何排序....


<html>
<body>

<p id="demo">Click the button to sort the array.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});
var x=document.getElementById("demo");
x.innerHTML=points;
}
</script>

</body>
</html>

试试这个功能更简单...

于 2013-06-06T06:43:38.133 回答