本文介绍了通过for循环连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过for loop
连接字符串,但是我正在接收NaNs
.我要实现的是获得一个串联的字符串Div #0, Div #1, Div #2, Div #3,
.
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,
.
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>
推荐答案
不要在var str
循环内声明新的str
变量.重用您在循环外部声明的代码.也做+=
Don't declare a new str
variable inside the loop with var str
. Reuse the one you declare outside the loop. Also do +=
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>
这篇关于通过for循环连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!