简体   繁体   English

对象的第一个结果返回undefined

[英]First result of object returns undefined

Description of Problem ( Fiddle ): 问题描述( 小提琴 ):

The first printed result of this code return 'undefined'. 此代码的第一个打印结果返回'undefined'。 Why? 为什么? And what would be the proper implementation to avoid it? 什么是适当的实施来避免它?

Code: 码:

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

JSFiddle 的jsfiddle

NOTE: At first your variable html had no value, so it was considered like undefined 注意:首先你的变量html没有值,所以它被认为是undefined

Fiddle Demo 小提琴演示

change 更改

var html; // default value is undefined

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM