jamesBondFilms.length stored in a variable.
There were 25 films. to see who starred.
uses the forEach method on jamesBondFilms.
Code here uses jamesBondFilms which is an array of objects, each of which is the name of a Bond film. Each object contains the following 5 properties:
titleof the filmyearthe film was releasedactorwho played James Bondnumthe number of the film (first film = 1).bondGirlthe main female character of the filmimdbthe IMDB rating for the film
These are stored in the pure-data.js file. The objects were created using an object constructor function:
function BondFilm(title, year, actor, num, bondGirl, imdb) {
(this.title = title),
(this.year = year),
(this.actor = actor),
(this.num = num),
(this.bondGirl = bondGirl),
(this.imdb = imdb);
}
The this keyword refers to an empty object.
Next each bond film object is created using the above arguments:
const drNo = new BondFilm(
"Doctor No",
1962,
"Sean Connery",
1,
"Ursula Andress",
7.2
);
The keyword new does 3 things:
- It creates a new empty object.
- It sets
thisto point to this object - It returns that object from the function
function titleList() {
const filmList = document.getElementById('film-list');
filmList.innerHTML = '';
let i = 0;
jamesBondFilms.forEach((item) => {
i = i+ 1;
console.log(item.title);
filmList.innerHTML += `${i}. ${item.title} (${item.year}) with ${item.actor}.<br>`;
});
};
Generating a random number
The random Bond girl button works like this:
- Firstly generates a random number using
Math.random(). - As the number is a decimal between 0 and 1 multiply it by 100.
- Since we only need numbers between 0 and 24 (25 films) divide by 4
- 100/4 = 25 hence multiplying by 25.
- Finally we only want whole integers so
Math.Roundis used to round up or down to the nearest whole integer. - This is stored in a variable called
randomFilmNumwhich is used as the index of the array of Bond films,jamesBondFilms.
let randomFilmNum = Math.round(Math.random() * 25);
alert(jamesBondFilms[randomFilmNum].bondGirl);
Note that the variable randomFilmNum is declared inside the onclick declaration so that it is re-run every click of the button. If it was declared outside, in a <script> tag before the button it would only be generated once when the page loads rather than every click of the button.
Conclusion
order
The JS here is in 3 places: in the HTML (using onclick), in <script> tags at the bottom of the page and in an external file pure-data.js which is linked in the <head> of the page.
Variables declared in the bottom <script> tags don’t work in the HTML onclick attributes.
Film titles
The Bond films are stored in an array of objects each of which has a different name, eg. noTimeToDie. Converting these camel case names would be a pain so it’s useful to include a title property in each object too.