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
Concatenate string through for loop
提问by nehel
I'm trying to concatenate strings via for loop
but 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 str
variable 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 forEach
if you have a list of stuff to put inside those divs
:
除了选定的答案之外,forEach
如果您有一个要放入其中的内容列表,则可以使用 a 执行此操作divs
:
let string = '';
items.forEach(item => string += '<div>'+ item.description + '</div>');