繁体   English   中英

未定义 - 烦人的 JavaScript 错误

[英]undefined - annoying JavaScript bug

我有以下代码,但无法理解为什么在列出我的对象属性之前会得到“未定义”? 我做错了什么吗?

正如您所知道的,我是 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; 声明变量并(隐式)赋予它一个初始值undefined

player_profile += some_string然后附加一个字符串。 这会将undefined转换为字符串,其结果是"undefined"

如果你希望初始值是一个空字符串,那么明确地说:

let 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM