I am very new to JavaScript and struggling through a book and completing exercises.
Can someone help explain to me what is happening in this loop and what is being stored in the array at the end?
I understand that it is setting image.src to "href" value in the HTML, but why does it need link before getAtribute? Where is it storing the "href" and the "title"?
"use strict";
var $ = function (id) { return document.getElementById(id); };
var imageCache = [];
var i, link, image;
for ( i = 0; i < links.length; i++ ) {
link = links[i];
image = new Image();
image.src = link.getAttribute("href");
image.title = link.getAttribute("title");
imageCache[imageCache.length] = image;
}
Thanks in advance for your help! This community has been a lifesaver while working though this.
2 Answers 2
but why does it need link before getAtribute
If you google getAttribute, you can see that it is a method called on a HTML element. So links seems to be an array of HTML elements (probably link elements).
Where is it storing the "href" and the "title"?
It stores them as properties of this object: image = new Image().
3 Comments
As mentioned in a comment you didn't show us what the links array looks like. However, assuming it's an array of DOM element links, here's a walkthrough of that code:
"use strict";
var $ = function (id) { return document.getElementById(id); };
var imageCache = [];
var i, link, image;
//looping through every element of links array
for ( i = 0; i < links.length; i++ ) {
link = links[i]; //this is the link we're at in the loop, making it easier to reference
image = new Image(); //creating a new Image element
image.src = link.getAttribute("href"); //set the src attribute of the image to the href of the link
image.title = link.getAttribute("title"); //set the title of the image to the title of the link
imageCache[imageCache.length] = image; //put the image in the imageCache array for use later
}
That being said, I think you might look into Array.map() as an alternative way to transform the one array of links into another array of images.
2 Comments
console.log(imageCache) at the end to see what imageCache contains in the console
linksyour code is uncompleted...imageCache[imageCache.length] = imagewhen it could just doimageCache.push(image)which will automatically add an item to the end of the arrayvar links = listNode.getElementsByTagName("a");Is there a benefit from usingimageCache[imageCache.length] = image?