简体   繁体   English

串联字符串节点

[英]Concatenate string node in loop

I've the following code and its working if result[1] have length is 1 like following: 我有以下代码,如果result[1]长度为1,则如下所示:

var url = redir[0] + 'value=' + encoURL + '& + result[1];

Now I have scenario when result have more entries 3 or five and I need to concatenate it to the string,there is nice way to do it instead of this ugly way 现在我有一个方案,当结果具有更多的条目3或5时,我需要将其连接到字符串,这是一种很好的方法来代替这种丑陋的方法

var url = redir[0] + 'value=' + encoURL + '& + result[1] + '& + result[2] + '& + result[3]  

and etc. 等等。

I have use lo-dash and underscore ... 我有使用破折号下划线 ...

From your example it looks as if you want all the results appended to the value, delimited by ampersands. 从您的示例看来,您似乎希望将所有结果附加到该值(以“&”号分隔)之间。 If that is what you want then this will do what you need... 如果那是您想要的,那么它将满足您的需求...

// get a copy of result, with the first element removed...
var newResult = result.slice(1);
var url = redir[0] + 'value=' + encoURL + (newResult.length ? "&" : "") + newResult.join("&");

join will concatenate all the values of newResult , delimited by an ampersand. join将连接newResult所有值, newResult以&符分隔。

(newResult.length ? "&" : "") basically adds the first ampersand if there are any values in newResult , so it handles the possibility that newResult is empty. (newResult.length ? "&" : "")如果newResult有任何值,则基本上添加第一个与newResult ,因此它可以解决newResult为空的可能性。 You could also put the join inside that conditional operator, but I did it like this as it's more readable, and it makes no difference to the end result. 您也可以将连接放入该条件运算符中,但是我这样做是因为它更具可读性,并且对最终结果没有影响。

I created newResult so you still have the original result array intact, in case you need it later. 我创建了newResult因此您仍然可以保留原始结果数组,以防日后需要时使用它。

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

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