red_panda
red_panda

Reputation: 344

Javascript print arrays

<!DOCTYPE html>
<html>
<head>
    <title>100-Numbers</title>
</head>
<body>
    <script>
    function myarray()
      var points = [];
      for (var i = 0; i < 10000; i++) {
          points.push[Math.round(Math.random() * 10)];
          document.write(myarray(points));
      }
    </script>
    <<button onclick="myarray"> OK </button>>
</body>
</html>

I am a beginner with javascript. I want to create a page that displays random numbers from 0 - 10. I am struggling to print an array. Is there a simple solution to this?

Upvotes: 0

Views: 623

Answers (7)

Satish Chandra Gupta
Satish Chandra Gupta

Reputation: 3361

I found few mistakes both in javascript and HTML side + 1 never to do mistake

Some points are already mentioned in the accepted answer but here are a few new ones.

JavaScript Part

  1. In your function myarray you have not used curly braces {}. All the codes of a function lie inside it.
  2. The push is an array method so use a small bracket () not square bracket with it.
  3. You are calling myarray function inside myarray function which causes infinite recursion.
  4. (A never to do mistake) - You wanted to print array on webpage, never use document.write method, because when document.write is executed after a webpage is loaded it overwrites everything on the page. Instead you can use console.log or select an element and inject data in it using innerHTML method. (shown in the code below)
  5. To print an array in javascript you can use index value with the array name. You can parallel print array elements as it is being pushed it reduce execution time. See in the code.

<!DOCTYPE html>
<html>

<head>
  <title>100-Numbers</title>
</head>

<body>
  &lt;<button onclick="myarray()"> OK </button>&gt;
  <p id="output"></p>
  <script>
    const output = document.getElementById("output");
    function myarray() {
      var points = [];
      for (var i = 0; i < 10000; i++) {
        points.push(Math.round(Math.random() * 10));
        output.innerHTML += points[i]; // printing array
      }
    }
  </script>
</body>

</html>

HTML Part

One can't say these mistake but rather some modifications (also there is a mistake in the button).

  1. (mistake) When you added onclick event listener to the button then call the function there, by adding parenthesis otherwise function will not execute on button click. Ex: onclick="myarray" => onclick="myarray()"
  2. You should not use angle brackets directly in HTML, it confuses the browser whether it is part of a tag or not. Instead use HTML entity. For < use &lt; and for > use &gt;
  3. Also you can put script tag at bottom of body it looks clean.

Upvotes: 0

Jahnavi Sananse
Jahnavi Sananse

Reputation: 118

//Arrow Function Expression
const demo = () => {
  var temp = [];
  for (var i = 0; i < 100; i++) {
    temp.push(Math.round(Math.random() * 10));
  }
  return temp;
}
console.log(demo());

//Normal Function Expression
function demo() {
  var temp = [];
  for (var i = 0; i < 100; i++) {
    temp.push(Math.round(Math.random() * 10));
  }
  return temp;
}
console.log(demo());

Upvotes: 0

Techuila
Techuila

Reputation: 1287

You also need to make an another element or tag so we can place and show the result of our random numbers.

And render the result using something like this:

document.getElementById('generate-number').innerHTML = random_array.

Next, if you render the array directly to an element, it will output with a delimiter, which is a comma ,. The sample output would look like: 2,6,2,1,6. So if you don't want any delimiter, you can remove it by using the .join() function: random_array.join('').

Here's a working example to try:

function generateArray() {
  // Creates 10 random numbers in an array
  const rand_num_arr = new Array(10).fill(null).map(e => Math.floor(Math.random() * 10));

  // Converts array into a string using .join()
  const rand_num = rand_num_arr.join(''); 

  // Display the random number in your div element "#generate-number"
  document.getElementById('generate-number').innerHTML = rand_num;
}
<div id="generate-number"></div>

<button onclick="generateArray()">Generate Random Numbers</button>

Upvotes: 0

DecPK
DecPK

Reputation: 25398

  • You need to call the function to get the result intended.
  • points is an array and push is a function so it can be called using ().

function myarray() {
  var points = [];
  for (var i = 0; i < 10000; i++) {

    const randomNumber = Math.round(Math.random() * 10);
    points.push(randomNumber);
  }
  document.write(points);
}
<button onclick="myarray()"> OK </button>

Upvotes: 0

T J
T J

Reputation: 43156

You have some syntax errors as well as logic errors.

  1. As pointed out in comments, for loop isn't executed.
  2. A function is defined like function myarray() {}
  3. A function is called with () like this myarray()
  4. Array.push() is a method that you invoke using ().
  5. You also seem to have rogue < in the HTML.

You can use an HTML element (In this case a <output> to display the contents of Array. The join('') method converts array content to a string.

function myarray() {
  const el = document.querySelector('output');
  var points = [];
  for (var i = 0; i < 10; i++) {
    points.push(Math.round(Math.random() * 10));
  }
  el.innerText = points.join('');
}
<button onclick="myarray()"> OK </button> 
Results: <output></output>

Upvotes: 0

Charlie
Charlie

Reputation: 23768

There are too many syntax errors in your code and thsi suggests that you need a proper tutorial than an answer. However, the following snippet shows the conventional way of doing what you want.

    function myarray(){
    
      var points = [];
      
      for (var i = 0; i < 10; i++) {
          points.push(Math.round(Math.random() * 10));     
         
      }
     
       document.getElementById('mySpan').innerHTML = 'Randoms: ' + points.toString();
    }
    
    myarray()
<span id="mySpan"></span>

Upvotes: 0

Barmar
Barmar

Reputation: 780724

  1. You should call the function from outside the function, not in the loop.
  2. The function can just return the array, you can print it in the caller.
  3. points.push is a function, you call it with (), not [].
  4. You're missing {} around the function body.
  5. The function doesn't take any arguments.

function myarray() {
  var points = [];
  for (var i = 0; i < 100; i++) {
    points.push(Math.round(Math.random() * 10));
  }
  return points;
}

console.log(myarray());

Upvotes: 2

Related Questions