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

112
Visualizações
how to fetch a value from specific index of object property that has the values of pushed array in javascript

I am trying to get a value from specific index of object property. I have used push function to push the value to object property, but when I call result.marks[0], it returns all the values in an array.

<!DOCTYPE html>
<html>

    <body>
        <p id="demo"></p>
        <script>
        try {
            let result = {
                marks: [], // 
            };
            const n = 5;
            let text = "";
            for (let i = 0; i < n; i++) {
                text += prompt("Enter value of " + i, i) + "<br>";
            }
            result.marks.push(text);
            document.getElementById("demo").innerHTML = result.marks[0]; // it does not print the specific index value.it return the whole values in an array.
        }
        catch (err) {
            document.write(err);
        };
        </script>
    </body>

</html>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Inside your loop you concatenate all the inputs in one string and push that one string to array.

loop 1: text="0<br>"
loop 2: text="0<br>1<br>"
and so on.

at the end of your loop your text value is "0<br>1<br>2<br>3<br>4<br>5<br>" and then you push it to array

so when you fetch the index 0 element it returns the string with all values. What you can do is stop concatenating and push each input to array inside the loop

<html>

    <body>
        <p id="demo"></p>
        <script>
        try {
            let result = {
                marks: [], // 
            };
            const n = 5;
            let text = "";
            for (let i = 0; i < n; i++) {
                text = prompt("Enter value of " + i, i) + "<br>";
                result.marks.push(text)
            }
            document.getElementById("demo").innerHTML = result.marks[1]; // it now returns value from specific index.
        }
        catch (err) {
            document.write(err);
        };
    </script>
</body>

</html>

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