问题
I'm the perfect case of the "most computer savvy guy gets the task." On the website I'm making, I need to sort a large number of names. The names change often, and lots of people change them. The number of names also change, so indexing by number would also not be a good thing.
My sample code I found looks like this:
<script type="text/javascript">
var fruits = ["Banana<br />", "Orange<br />", "Apple<br />", "Mango<br />",];
document.write(fruits.sort());
</script>
This works with the exception that the commas are displayed on the website. This isn't acceptable. I'm looking for a way to make the commas go away from the website when it's displayed.
回答1:
An array isn't a string, and the default way of converting it is to join the elements by ,
. Just specify your own joining string instead:
var fruits = ["Banana<br />", "Orange<br />", "Apple<br />", "Mango<br />",];
document.write(fruits.sort().join('')); // Don't join by anything
回答2:
The sort method returns the sorted array. You could apply it the join method to concatenate all elements of this array using a separator before outputting it:
document.write(fruits.sort().join(''));
回答3:
In this case the commas are being displayed because you are writing an collection to the document and hence a separator is being displayed. To avoid this write out the entries manually
for (var i = 0; i < fruits.length; i++) {
document.write(fruits[i]);
}
Note: It's generally better practice to separate data from display. In this case you mixed the data (fruit name) with the display information (<br/>
). Another way to consider writing this is the following
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
for (var i = 0; i < fruits.length; i++) {
document.write(fruits[i]);
document.write("<br/>");
}
来源:https://stackoverflow.com/questions/9446321/sort-array-without-displaying-commas