我有以下代码,无法理解为什么在列出对象属性之前我得到'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);
答案 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);