[英]How to find the index of an object in an array by checking property value in JavaScript?
[英]how to fetch a value from specific index of object property that has the values of pushed array in javascript
我正在嘗試從 object 屬性的特定索引中獲取值。 我使用 push function 將值推送到 object 屬性,但是當我調用result.marks[0]
時,它返回數組中的所有值。
<!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>
在您的循環中,您將所有輸入連接到一個字符串中並將該字符串推送到數組。
loop 1: text="0<br>"
loop 2: text="0<br>1<br>"
and so on.
在循環結束時,您的文本值為"0<br>1<br>2<br>3<br>4<br>5<br>"
,然后將其推送到數組
因此,當您獲取索引 0 元素時,它會返回包含所有值的字符串。 您可以做的是停止連接並將每個輸入推送到循環內的數組
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.