I have the following code and cannot understand why I am getting an 'undefined' before my object properties are listed..? Am I doing something obviously wrong?
As you can tell I am a newbie to JavaScript, any help is majorly appreciated!
let player_profile; const players = [ { name: "George Ford", age: 22, position: "Back" }, { name: "Ben Youngs", age: 28, position: "Forward" } ]; for (let i = 0; i < players.length; i++) { player_profile += '<h2>Name: ' + players[i].name + '</h2>'; player_profile += '<p>Age: ' + players[i].age + '</p>'; } document.write(player_profile);
let player_profile;
declares the variable and (implicitly) gives it an initial value of undefined
.
player_profile += some_string
then appends a string to it. This converts undefined
to a string, the result of which is "undefined"
.
If you want the initial value to be an empty string, then say so explicitly:
let player_profile = "";
Because you've not initialized your player_profile:
let player_profile = "";
const players = [
{
name: "George Ford",
age: 22,
position: "Back"
},
{
name: "Ben Youngs",
age: 28,
position: "Forward"
}
];
for (let i = 0; i < players.length; i++) {
player_profile += '<h2>Name: ' + players[i].name + '</h2>';
player_profile += '<p>Age: ' + players[i].age + '</p>';
}
document.write(player_profile);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.