I'm working on a lab for my Javascript class and it is a lab dedicated to custom objects and constructor functions. object. I'm making a custom object some musical artists I like. Creating a list of my favorites that I can repeatedly access. I made a constructor function(Called musicalArtist) that creates the musical artists. Passed the arguments through And then stored the custom object in an array. I then created another function called showInfo(). On the first line, I entered the following code:
var info = “ ”
This creates an empty string that I can add information to as I run through the objects. Then I created a for loop that has a counting variable named count set to 0. And inside the forloop I added details about the objects to the info variable. When the user clicks the button it's supposed to run the showInfo() function but it does not? Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<title> Custom Objects Lab</title>
<script>
function musicalArtist(name, song, description){
this.name = name;
this.song = song;
this.description = description;
}
var t= new musicalArtist("Tyler the Creator", "All of them", "He's
beautiful I might cry");
var s= new musicalArtist("Slipknot", "Wait and Bleed", "Literally so
awesome");
var a= new musicalArtist("Ayesha Erotica", "Literal Legend", "She is
such an icon");
var myArtists = [t];
var myAritsts= [s];
var myAritsts = [a];
function showInfo() {
var info = ""
for (var count = 0; count < 3; count++) {
info += "Name:" + myAritsts[count].name + "\n";
info += "Best Song:" + myAritsts[count].song + "\n";
info += "Descrition:" + myAritsts[count].description +
"\n";
}
alert(info);
}
</script>
</head>
<body>
<button onclick="showInfo()">A</button>
</body>
</html>
Your code is very close to working. While @stroeda's suggestion to use event listeners is more commonly used these days, that is not what is stopping your code from working.
Some notes to lead you in the right direction:
1) It is convention when defining a constructor to begin your function name with a capital letter. So, instead of function musicalArtist
use function MusicalArtist
. This does not change the functionality, but will be expected if others are looking at your code.
2) Each time you write var myArtists = [something]
you are overwriting the previous myArtists
array. What you want is an array with three artists in it.
3) If you are trying to iterate over an entire array, you would be better off using the length
property of the array, rather than hardcoding the assumed length of 3. That way, if the length changes, your code will be able to handle it.
4) Be sure to check your spelling. A single typo can break your entire program. You have a typo in there that will break your code. If you write your code in an editor like VS Code and use a linter it will be easier to spot typos.
Good luck with the class!