Code for reversing an array in JavaScript fails
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);
I'm trying to make a reve开发者_C百科rse of the ordered (a-z) array fruits, in order to make it z-a in the for loop. Why isn't this working?
Just use .reverse()
.
fruits.reverse();
精彩评论