undefined - 恼人的JavaScript bug

时间:2017-12-26 16:23:32

标签: javascript

我有以下代码,无法理解为什么在列出对象属性之前我得到'undefined'。?我做了一件明显不对的事吗?

正如您所知,我是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);

2 个答案:

答案 0 :(得分:2)

let player_profile;声明变量并(隐式)为其赋予初始值undefined

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

如果您希望初始值为空字符串,请明确说明:

let player_profile = "";

答案 1 :(得分:2)

因为你没有初始化你的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);