此代码的第一个打印结果返回'undefined'。为什么?什么是适当的实现来避免它?
var animals = {
dogs: 0,
cats: 0,
birds: 0,
fish: 0
};
function countAnimals(animal) {
animals[animal]++;
var html;
for (var key in animals) {
if (animals.hasOwnProperty(key)) {
html += key + ': ' + animals[key] + '<br/>';
}
}
$('#output').html(html);
};
countAnimals('dogs');
答案 0 :(得分:1)
var animals = {
dogs: 0,
cats: 0,
birds: 0,
fish: 0
};
function countAnimals(animal) {
animals[animal]++;
var html = ""; // here define variable as a string
for (var key in animals) {
if (animals.hasOwnProperty(key)) {
html += key + ': ' + animals[key] + '<br/>';
}
}
$('#output').html(html);
};
countAnimals('dogs');
注意:首先,您的变量html
没有任何价值,因此它被视为undefined
答案 1 :(得分:1)