Jump to content

quick array question


Recommended Posts

i have a question. i did a quick person array. ive used both a for and for in loop to loop through it. they give me the same results. If i alert the results, i get a separate alert for each element in my array. but if i use document.wrtie, my code only writes out the 1st element, "john". can anyone tell me why this is happening: <!DOCTYPE html><html><body><button onclick="myFunction()">Try it</button><script type="text/javascript">function myFunction(){var x;var person=["John","Pete","Ray"];for (x in person){document.write(person[x]);//alert works fine but not document.write}}</script></body></html>

Link to post
Share on other sites

It's usually because when using document.write, it basically makes a new document. So in your case, what it's doing is making a new document and printing the first value in the array, John thus why you only see John but some browsers may display all values in the array.

Edited by Don E
Link to post
Share on other sites

I'm curious where document.write() output really goes? Creates new document? Adds to end of document? I don't think I've ever used it in JS but several other languages have very similar commands.

Link to post
Share on other sites

From my experience with it, if you're using it without calling by some onclick event for example, it will just write to the current document. If you call it by some onclick event for example, it will make a new document. For example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>document write</title><script type="text/javascript">	 function sayHello()	 { 		  document.write("<h1>hello by onclick</h1>");	 } </script></head> <body><button type="button" onclick="sayHello();">Click here</button> <script type="text/javascript">document.write("<h1>hello by document.write on current page</h1>");</script></body></html>

Edited by Don E
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...