Home > database >  how to fetch a value from specific index of object property that has the values of pushed array in j
how to fetch a value from specific index of object property that has the values of pushed array in j

Time:02-23

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.

<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>

CodePudding user response:

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>

  • Related