将变量插入JavaScript中的对象名称
如果您查看下面发布的JSON,我有几个名为Row0,Row1,Row2等的对象...
我在下面进一步发布的代码工作,但不按预期发布。问题在于以下行:
for (let key in movies.row1) {
我硬编码row1,但我真的想实现的是row1,然后row2,然后row3等...
因此,我想将i的值插入词行之后的对象的名称中...
Movie.Rowi< ---我需要成为一个变量而不是字母i。
我尝试了谷歌搜索和stackoverflow的一些猜测。另外,尝试传播操作员之类的东西。
function display_all_movies(movies) {
for (i = 0; i < movies.row_count.count; i++) {
for (let key in movies.row1) {
document.getElementById("moviesList").innerHTML += `Key: ${key}` + `Value: ${movies.row1[key]}` + '<br>';
}
}
}
电影是JSON格式的对象,已验证。电影JSON如下:
{"row0" : {"title":"Avengers","imgName":"Avengers.jpeg","addedBy":"MrCoolDude","stars":"4"},"row1" : {"title":"Spiderman","imgName":"Spiderman.jpeg","addedBy":"TheNumber2Dude","stars":"5"},"row2" : {"title":"Conair","imgName":"conair.png","addedBy":"Eagleuser","stars":"3"}, "row_count" : {"count" : "4"},"row3" : {"title":"Robin","imgName":"Robin.jpeg","addedBy":"UserBatman","stars":"4"}}
If you look at the JSON posted further below, I have several objects named row0, row1, row2 etc...
The code I posted further below works but not as intended. The problem lies with the following line:
for (let key in movies.row1) {
I hard coded row1 but I really want to achieve is row1 then row2 then row3 etc...
So I want to insert the value of i into the name of the object after the word row...
movies.rowi <--- i needs to be a variable not the letter i.
I tried a few guesses from googling and stackoverflow like movies.row${[i]} but nothing worked. Also, tried spread operator something like movies.row[1...6] but its invalid.
function display_all_movies(movies) {
for (i = 0; i < movies.row_count.count; i++) {
for (let key in movies.row1) {
document.getElementById("moviesList").innerHTML += `Key: ${key}` + `Value: ${movies.row1[key]}` + '<br>';
}
}
}
movies is an object in JSON format, which is validated. Movies JSON is as follows:
{"row0" : {"title":"Avengers","imgName":"Avengers.jpeg","addedBy":"MrCoolDude","stars":"4"},"row1" : {"title":"Spiderman","imgName":"Spiderman.jpeg","addedBy":"TheNumber2Dude","stars":"5"},"row2" : {"title":"Conair","imgName":"conair.png","addedBy":"Eagleuser","stars":"3"}, "row_count" : {"count" : "4"},"row3" : {"title":"Robin","imgName":"Robin.jpeg","addedBy":"UserBatman","stars":"4"}}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用括号符号进行动态属性访问。
Use bracket notation for dynamic property access.