简体   繁体   English

通过 for 循环连接字符串

[英]Concatenate string through for loop

I'm trying to concatenate strings via for loop but i'm receiving NaNs .我正在尝试通过for loop连接字符串for loop但我正在接收NaNs What i want to achieve is to get one concatenated string Div #0, Div #1, Div #2, Div #3, .我想要实现的是获得一个连接字符串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>

Don't declare a new str variable inside the loop with var str .不要在循环中使用var str声明一个新的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>

Besides the selected answer, you could do this with a forEach if you have a list of stuff to put inside those divs :除了选定的答案之外,如果您有要放入这些divs的内容列表,则可以使用forEach执行此操作:

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

If we are concatenating the string for an array then you can do like this.如果我们连接数组的字符串,那么您可以这样做。 For loop is also best solution but it becomes vast process: For 循环也是最好的解决方案,但它变成了一个庞大的过程:

if(this.questionData.length > 0) {
    this.questionData.forEach(questions => {this.questionsParams += '&question'+ questions.question +'=' + questions.value;
    });
}

Perfect solution output like this : &question1=1&question2=0&question3=1&question4=0完美的解决方案输出如下: &question1=1&question2=0&question3=1&question4=0

let str = '';
for (const i of [...Array(divLength).keys()]) {
  str += `Div #${i}, `;
}
console.log(str);

or a one-liner alternative,或单线替代品,

console.log(`${[...Array(divLength).keys()].map(val => ` Div #${val}`)}`.substr(1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM