[英]undefined - annoying JavaScript bug
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!正如您所知道的,我是 JavaScript 的新手,非常感谢任何帮助!
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
.声明变量并(隐式)赋予它一个初始值
undefined
。
player_profile += some_string
then appends a string to it. player_profile += some_string
然后附加一个字符串。 This converts undefined
to a string, the result of which is "undefined"
.这会将
undefined
转换为字符串,其结果是"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:因为你还没有初始化你的 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.