代码返回'undefined'

时间:2014-10-12 22:54:54

标签: javascript

为什么这段代码会返回undefined

http://jsfiddle.net/hdy3grgj/

function getMoods(nb) {
        var index;
        var moods;
        var a = ["MOOD0001", "MOOD0002", "MOOD0003", "MOOD0004", "MOOD0005", "MOOD0006", "MOOD0007", "MOOD0008", "MOOD0009", "MOOD0010", "MOOD0011", "MOOD0012", "MOOD0013", "MOOD0014", "MOOD0015", "MOOD0016"];
        for (index=0; index<=nb; ++index) {
                if(index==0 || index==4 || index==8 || index==12) { moods += '<div class="col-xs-4">'; }
                        moods += 
                                '<div class="checkbox">'
                                    +'<label for="'+a[index]+'">'
                                        +'<input type="checkbox" id="'+a[index]+'" class="moods"> '+a[index]
                                    +'</label>'
                                +'</div>';
                if(index==3 || index==7 || index==11) { moods += '</div> '; }
        }
        $("#moods-area").html(moods);
}
getMoods(12)

3 个答案:

答案 0 :(得分:1)

您在字符串的开头会出现“未定义”,因为您没有为moods设置值,并为其添加字符串。然后它会将moods转换为字符串,结果为“未定义”,并向其添加一些内容。要解决此问题,请使用var moods="";代替var moods;

答案 1 :(得分:1)

moods的初始值为undefined。看看我在未初始化的变量中添加字符串时会发生什么:

> var foo;
> foo + 'bar';
"undefinedbar"

解决方案:使用空字符串初始化变量。

答案 2 :(得分:1)

因为moods的初始值是undefined,因为它从未被it(声明,是;初始化,否);变化:

var moods;

为:

var moods = '';

没有&#39; undefined&#39;:JS Fiddle demo