Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help with array sort 2

Status
Not open for further replies.

bookouri

IS-IT--Management
Feb 23, 2000
1,464
US
I'm working with javascript for the first time on a web site. Can somebody tell me what's going on with this:

It comes out just fine and gives me a randomised list of "companies" which is what i want.. but the list is seperated by commas...

company 1a

,
company 2a

,
company 3a etc...

where are the "commas" coming from and can i get rid of them?



<script language=JavaScript>
var company=new Array()
company[0]='<p>Company 1a</p> <br/>'
company[1]='<p>Company 2a</p> <br/>'
company[2]='<p>Company 3a</p> <br/>'
company[3]='<p>Company 4a</p> <br/>'
company[4]='<p>Company 5a</p> <br/>'
company[5]='<p>Company 6a</p> <br/>'
company.sort(function() {return 0.5 - Math.random()});
document.write(company);
</script>


thanks for any suggestions
 

Loop through the elements of the array:

Code:
for (i = 0; i < company.length; i++)
        document.write(company[i]);


Mark

"You guys pair up in groups of three, then line up in a circle."
- Bill Peterson, a Florida State football coach
 
Hi

Using multiple [tt]document.write()[/tt]s when one is enough is bad practice. That puts the rendering engine to process the document again after each modification.

The [tt]Array.toString()[/tt] forced by handling [tt]Array[/tt] as [tt]String[/tt] actually just does an [tt]Array.join()[/tt], which has comma ( , ) as default separator. Just specify empty string instead :
Code:
document[teal].[/teal][COLOR=darkgoldenrod]write[/color][teal]([/teal]company[highlight][teal].[/teal][COLOR=darkgoldenrod]join[/color][teal]([/teal][green][i]''[/i][/green][teal])[/teal][/highlight][teal]);[/teal]

Feherke.
 
faherke, thanks
I tried your suggestion and it worked. In this small example I can't tell about the performance but it makes sense.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top