[英]First result of object returns undefined
The first printed result of this code return 'undefined'. 此代码的第一个打印结果返回'undefined'。 Why?
为什么? And what would be the proper implementation to avoid it?
什么是适当的实施来避免它?
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');
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');
NOTE: At first your variable html
had no value, so it was considered like undefined
注意:首先你的变量
html
没有值,所以它被认为是undefined
change 更改
var html; // default value is undefined
to 至
var html=''; //set value as empty string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.