angel7
angel7

Reputation: 5

Beginner JavaScript for loop

I was wondering if anyone knows the reason for [i-1] in the fourth line when you also have i++ in the second line? Thank you for any help! (It's from the book "JavaScript" by Vodnik and Gosselin.)

if (figureCount === 3) {

for (var i = 1; i < 4; i++) {
filename = "images/IMG_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByTagName("img")[i - 1];
currentFig.src = filename;
}//end of for loop

Upvotes: 0

Views: 63

Answers (3)

Plixxer
Plixxer

Reputation: 466

Some developers get confused with the for loop operators logic instead of doing it correctly:

for (var i = 0; i < 3; i++) {

they decided to add some extra processing to the mix ( which isn't that big of a deal ) but iv'e fired developers for less.

CurrentFig is using i - 1 because it appears there is a prepended img element so the developer also chose to select it as well instead of selecting the exact elements that he needs.

Upvotes: 0

brk
brk

Reputation: 50291

document.getElementsByTagName return a HTMLCollection which is not an array but an array like object. So to access any element from that collection you can pass the index.

document.getElementsByTagName("img")[i - 1] is creating a collection of all the img tags & it is accessing specific element in that collection by passing the index [i-1]

In the below example [1] is trying to access the second element from the collection

var getAllDiv = document.getElementsByTagName('div');
console.log(getAllDiv[1].innerHTML)
<div>1</div>
<div>2</div>

Upvotes: 1

Hozefa
Hozefa

Reputation: 1726

It because document.getElementsByTagName returns an HTMLCollection(similar to array) hence. So accessing the 1st(and subsequent) img tag on the page are done through setting i-1

Upvotes: 2

Related Questions