在JavaScript中反转数组的代码失败

时间:2010-12-23 22:04:59

标签: javascript arrays sorting

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits = fruits.sort();
document.write(fruits);
for(var i = 0; i < Math.ceil(fruits.length / 2); i++) {
    var temp = fruits[i];
    fruits[i] = fruits[fruits.length - 1 - i];
    fruits[fruits.length - 1 - i] = temp;
}
document.write(fruits);

我试图反转有序(a-z)数组,以便在for循环中使其成为z-a。为什么这不起作用?

1 个答案:

答案 0 :(得分:6)

Just use .reverse().

fruits.reverse();