Skip to content
Advertisement

For Loop is Not Running Khan Academy Project:Bookshelf [closed]

“This program only displays one book. Make an array of books (at least two of them), and use a loop to display a row of them.”

I want to use the for loop to draw the other book in the array. In the current state, i remains 0, and must be manually set to 1 to draw the next book.

var book = [
{title: "I Know Why the Caged Bird Sings",
stars: 4,
like:false},
{title: "The Old Man and the Sea",
stars: 5,
like:true}
];

// draw shelf
for (var s =1; s<4; s++) {
fill(173, 117, 33);
rect(0, s*120, width, 10);
}

// draw one book
for (var i = 0; i<book.length; i++){
var book = book[i]; //specifying the array
fill(214, 255, 219);
rect(i*97, 20, 90, 100);
fill(0, 0, 0);
text(book.title, i*97, 29, 70, 100);
for (var rating = 0; rating < book.stars; rating++) {
    image(getImage("cute/Star"),i*100+ rating * 19, 90, 18, 30);
}
}

Advertisement

Answer

Use a different variable name for an individual book than the book array:

for (var i = 0; i<book.length; i++){
    var bookItem = book[i];        
    fill(214, 255, 219);
    rect(i*97, 20, 90, 100);
    fill(0, 0, 0);
    text(bookItem.title, i*97, 29, 70, 100);
    for (var rating = 0; rating < bookItem.stars; rating++) {
        image(getImage("cute/Star"),i*100+ rating * 19, 90, 18, 30);
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement