Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
page doesn't display anything

so I wrote a script to display 5 random arrays, but the page doesn't display anything.
here's the code:

<html>
  <head>
    <script>
      function start(){
        var arr(5),result;
        result=document.getElementById("arraying");
        result="<p>";
        for(var i=0; i<5;i++){
          arr[i]=Math.floor(Math.random()*10);
          result+="arr["+i+"]= "+arr[i]+"</p><p>";
        }
        result+="</p>";
      }
      window.addEventListener("load",start,false);
    </script>
  </head>
  <body>
    <div id="arraying"></div>
  </body>  
</html>

I tried removing result=document.getElementById and write document.getElementById.innerHTML=result in the end of the function but didn't work. what's the error?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You cannot use the same variable for different purposes at the same time. First you assign a DOM element to result, and immediately on the next line you overwrite result with a string.

Build a string htmlStr inside your loop, and when that is done, assign this string to result.innerHTML property:

function start() {
  let arr = [],
    result, htmlStr = '';
  result = document.getElementById("arraying");
  htmlStr += "<p>";
  for (let i = 0; i < 5; i++) {
    arr[i] = Math.floor(Math.random() * 10);
    htmlStr += "arr[" + i + "]= " + arr[i] + "</p><p>";
  }
  htmlStr += "</p>";
  result.innerHTML = htmlStr;
}
window.addEventListener("load", start, false);
<div id="arraying"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Looking at the code you seem to be missing some basic javascript concepts.

array size

This is probably your main issue:

var arr(5)

This does not make sense in javascript. Array length does not need to be predefined since all arrays are of dynamic length. Simply define an array like this:

var arr = []

Then later when you want to append new elements use push like this:

arr.push( Math.floor(Math.random()*10) )

adding html using innerHTML

There are different ways to dynamically inject html into your page. (It looks like) you tried to append the html as a string to the parent element. This is not possible.

You said you tried using innerHTML. That should work if used correctly.

A working implementation would work like this:

function start() {
 var arr = []
 var result = "<p>"
 for(var i = 0; i < 5; i++) {
  arr.push( Math.floor(Math.random()*10) ) // Btw this array isn't actually needed.
  result += "arr[" + i + "] = " + arr[i] + "</p><p>"
 }
 document.getElementById("arraying").innerHTML = result
}
window.addEventListener("load", start, {passive: true});

adding html using createElement

A generally better way of dynamically adding html elements is via createElement.

This way you dont have to write html and are therefore less prone for making errors. It is also more performant and easier to integrate into javascript.

I think the best explaination is a commented implementation:

function start() {
 var myDiv = document.getElementById("arraying") // get parent node
 var arr = []
 for(var i = 0; i < 5; i++) {
  arr.push( Math.floor(Math.random()*10) )
  var p = document.createElement("p") // create p element
  p.innerText = "arr[" + i + "] = " + arr[i] // add text content to p element
  myDiv.append(p) // append p element to parent element
 }
}
window.addEventListener("load", start, {passive: true});

small tips

The let keyword works mostly the same as the var keyword, but is generally preferred because of some edge cases in which let is superior.

Fusing strings and variables using the plus operator is generally considered bad practice. A better way to do the string concatenation would have been

result += `arr[${i}] = ${arr[i]}</p><p>`
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda