简体   繁体   中英

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM