FOR 循环和字符串与 JavaScript 连接给我一个未定义的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3992973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:06:06  来源:igfitidea点击:

FOR loop and string concatenating with JavaScript gives me an undefined value

javascript

提问by Morgan

I have the array

我有数组

var data = [name, address, city, country];

And the loop

和循环

var columns;
for (var i = 0; i < data.length; i++) {
    columns += "data[" + i + "], ";
}
columns = columns.slice(0, -2);
alert(columns);

The alert message says

警报消息说

undefineddata[0], data[1], data[2], data[3]

What am I doing wrong here? I want to remove the undefined...

我在这里做错了什么?我想删除未定义的...

回答by Nick Craver

You need to startwith an empty string, like this:

您需要一个空字符串开始,如下所示:

var columns = "";

Right now what you have is basically equivalent to:

现在你所拥有的基本上相当于:

var columns = undefined;

Which when concatenated to a string, gives you "undefined".

当连接到一个字符串时,会给你"undefined".