Insert javascript image

Asked

Viewed 12,407 times

-1

Boas, I want to insert an image according to the amount of times existing in the property of an object. It is easier to explain with an example:

I have this object:

var book = [
    {
        title: "O Tatuador de Auschwitz",
        stars: 4,
        Author: "Heather Morris",
        Validation: true
    }
]

and in this case I want to insert an image 4 times (according to the Stars property). To do this I created a cycle for as follows:

for (var s = 0; s < book.stars ; s++) {
            image(starj,s,100,20,20);
    }

starj this defined with the image I want to insert

what I’m doing wrong?

Thank you

P.S. I’m still very green in this..

  • You can give us the full code example you are using?

  • Welcome Tiagooliveira86, read this post for better answers https://answall.com/help/mcve

2 answers

1

Array index and field you want to get missing book[0]["stars"]:

var s;
var book = [
   {
       title: "O Tatuador de Auschwitz",
       stars: 4,
       Author: "Heather Morris",
       Validation: true
   }
];
for(s = 0; s < book[0]["stars"]; s++){
     var img = document.createElement("IMG");
     img.src = "https://i.imgur.com/F543MoZ.png";
     img.style.width = "30px";
     img.style.height = "30px";
     document.getElementById('imagens').appendChild(img);
}
<!DOCTYPE html>
<html>
<head>
   <title>teste</title>
</head>
<body>
   <div id="imagens"></div>
</body>
</html>

0

Thanks Gabriel, I found out what was missing. So I finished the code this way:

for (var i = 0; i < book.length; i++){
fill(random(0,250), random(50, 175) , 219);
rect(10+i*120, 20, 90, 100);
fill(0, 0, 0);
text(book[i].title, 15+i*120, 29, 70, 100);
text(book[i].Author, 15+i*120, 82, 70, 100 );
    for (var s = 0; s < book[i].stars; s++) {
        image(starj,(i*120)+(s*15),160,30,30);
    }

In this way, the image of the stars is inserted horizontally with the number of times present in the Stars property of the object Book.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.