Simplify / Optimize FOR

0

How can I simplify the second for , that is, I would like to improve it / optimize it, I see it as repetitive but I do not understand how to improve it:

var book =[ {
    title: "The Giver",
    stars: 4,
    author: "Manuel G. H.",
    color: color(255, 183, 0)
    },
    {
    title: "Adventures",
    stars: 5,
    author: "Humberto B.B",
    color: color(152, 234, 245)
    },
    {
    title: "Rock N Roll",
    stars: 2,
    author: "Buitrago M.H",
    color: color(0, 255, 0)
    }];

//Soporte para libros
fill(173, 117, 33);
rect(0, 120, width, 10);

for ( var books = 0 ; books < book.length ; books++){

    fill(book[books].color);
    rect(10 + books * 100, 20, 90, 100);

    fill(0, 0, 0);
    text(book[books].title, 23 + books * 100, 29, 70, 100);
    text(book[books].author, 23 + books * 100, 69, 70, 100);    
}

for (var i = 0; i < book[books].stars ; i++) {

            var space = 100;

            if(book[books].stars <= 4){
                image(getImage("cute/Star"), 12 + i * 17 , 90, 20, 30);
                espacio += 100;
            }
            if(book[books].stars <= 5){
                image(getImage("cute/Star"), 12 + space + i * 17, 90, 20, 30);

            }
            if(book[books].stars <= 2){
                image(getImage("cute/Star"), 12 + spcae + i * 17, 90, 20, 30);
            }        
}
    
asked by ManuelSZ18 09.04.2017 в 17:41
source

1 answer

1

In the code you have put there are several errors, regardless of what you want to do, although it is intuited is not very clear.

1) You are using a variable name in the singular book to refer to something that normally contains several things. It would be better to name it books .

2) In the first loop, the variable flame index books , which again leads to confusion. Use what everyone, i or as much book_idx . Each variable has to describe what it contains.

3) In the second loop you are using the variable books that is out of scope, since you declared it in the initialization part of% previous for . And even if it were still present in the current scope, it would have value 3 (the one that causes the previous loop to end), so book[books] will give you index error out of range. You may want to nest the second loop inside the first one.

    
answered by 09.04.2017 в 18:18