在Javascript中使用for循环对数组进行排序 [英] Sorting arrays using for loop in Javascript
本文介绍了在Javascript中使用for循环对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用 for循环 JavaScript按升序/降序排序数组?
Is it possible to sort arrays in ascending/descending order using the for loop JavaScript?
我一直在学习JS经历在课堂测试之前,教科书中的一些练习题。
I've been learning JS going through a few practice questions in a textbook before a class test.
任何指针都会受到赞赏!
Any pointers would be appreciated!
a = Number(prompt("a:"));
b = Number(prompt("b:"));
c = Number(prompt("c:"));
d = Number(prompt("d:"));
e = Number(prompt("e:"));
// find largest element
var test = [a, b, c, d, e];
var biggest = -Infinity;
var biggest_index = -1; {
for (i = 0; i < test.length; i++) {
if (test[i] > biggest) {
biggest = test[i];
biggest_index = i;
}
else;
}
alert("The biggest element is " + biggest + " at index " + biggest_index);
}
// move largest element of array to the last index
test[test.length] = biggest;
// get rid of copy
test[biggest_index] = 0;
alert("Unsorted: " + test);
// shuffle ??
推荐答案
如果你想获得最大/最小数量一个数组,为什么不使用 Math.max / Math.min
?
If you want to get the max/min number in an array, why not use Math.max/Math.min
?
如果要对数组进行排序,可以使用 sort
方法:
If you want to sort the array, you can use sort
method:
var sorted = [3, 1, 6, 2].sort(); // sort ascending
var sorted = [3, 1, 6, 2].sort(function(a, b){
return b - a;
}); // sort descending
这篇关于在Javascript中使用for循环对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文