Javascript 通过 for 循环连接字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39584129/
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-08-23 22:42:48  来源:igfitidea点击:

Concatenate string through for loop

javascriptjquery

提问by nehel

I'm trying to concatenate strings via for loopbut i'm receiving NaNs. What i want to achieve is to get one concatenated string Div #0, Div #1, Div #2, Div #3,.

我正在尝试通过连接字符串,for loop但我收到NaNs. 我想要实现的是获得一个连接的字符串Div #0, Div #1, Div #2, Div #3,

var divLength = $('div').length;

var str = '';
for(var i=0; i<divLength; i++){
  var str =+ "Div #" + [i] + ", ";
  console.log(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>

回答by Red Mercury

Don't declare a new strvariable inside the loop with var str. Reuse the one you declare outside the loop. Also do +=

不要str在循环内声明一个新变量var str。重用你在循环外声明的那个。也做+=

var divLength = $('div').length;

var str = '';
for(var i=0; i<divLength; i++){
  str += "Div #" + i + ", ";
  console.log(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>

回答by Sebastian D'Agostino

Besides the selected answer, you could do this with a forEachif you have a list of stuff to put inside those divs:

除了选定的答案之外,forEach如果您有一个要放入其中的内容列表,则可以使用 a 执行此操作divs

let string = '';
items.forEach(item => string += '<div>'+ item.description + '</div>');