Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!