对象的第一个结果返回undefined

时间:2014-03-07 14:03:12

标签: javascript jquery object associative-array

问题描述(Fiddle):

此代码的第一个打印结果返回'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');

2 个答案:

答案 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');

JSFiddle

注意:首先,您的变量html没有任何价值,因此它被视为undefined

答案 1 :(得分:1)

Fiddle Demo

变化

var html; // default value is undefined

var html=''; //set value as empty string