javascript - Creating Arrays Dynamically with a for loop -
i making application needs read 10 song names , 5 ratings per song. thing having 1 array each song store name , 5 different ratings ideal don't know how dynamically create arrays loop. ideas? here sample:
for (var song = 1; song < 11; song++) { prompt("give song title, no:" + " " + song); (var = 1; < 8; i++) { prompt("give song no:" + " " + song + " " + ", rating:" + i); } }
i suggest have array of objects, each object contains title , array of ratings, giving structure looks this:
[ { title: "first song", ratings: [ 5, 3, 4, 1, 4 ] }, { title: "second song", ratings: [ 2, 3, 2, 1, 1 ] } ]
create array first, create object each song empty array ratings. can put ratings in array:
var songs = []; (var song = 0; song < 10; song++) { var title = prompt("give song title, no: " + song); songs[song] = { title: title, ratings: [] }; (var = 1; <= 5; i++) { var rating = prompt("give song no: " + song + " , rating:" + i); songs[song].ratings.push(rating); } }
Comments
Post a Comment