Wednesday, 8 June 2016

Add The Array Elements Using A Loop In JavaScript

Let us consider an example:-

index.html:-

<html>
<head>
<body>
  <script src="app.js">
  </script>
</body>

</html>



app.js:-

var crap = new Array(5);

for(var i=0;i<5;i++)
{
  crap[i] = prompt("Add something in an array");
  document.write(crap[i]);
  document.write("<br/>");
  }



Output:-


Explanation:-

Here, we are entering every single element one by one in an array, by using the prompt() method in JavaScript. "crap" is the variable declared, within which an array of length 5 is included."document.write" is used in the JavaScript to print the data. Here, the element entered in the array are displayed on the screen one by one, once the user enters the data. "<br/>" is used to move the cursor to the next line.

No comments:

Post a Comment