在 Javascript 中向字符串添加字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5754712/
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
Add characters to a string in Javascript
提问by Bruno
I need to add in a For Loop characters to an empty string. I know that you can use the function concat in Javascript to do concats with strings
我需要将 For 循环字符添加到空字符串中。我知道你可以使用 Javascript 中的 concat 函数来对字符串进行连接
var first_name = "peter";
var last_name = "jones";
var name=first_name.concat(last_name)
but with my example it doesn't work. Any idea how to do it another way ?
但在我的例子中它不起作用。知道如何以另一种方式做到这一点吗?
my code :
我的代码:
var text ="";
for (var member in list) {
text.concat(list[member]);
}
回答by Blazes
var text ="";
for (var member in list) {
text += list[member];
}
回答by Matt Sich
You can also keep adding strings to an existing string like so:
您还可以继续向现有字符串添加字符串,如下所示:
var myString = "Hello ";
myString += "World";
myString += "!";
the result would be -> Hello World!
结果将是 -> Hello World!
回答by neebz
simply used the +
operator. Javascript concats strings with +
简单地使用了 +
运算符。Javascript 用 + 连接字符串
回答by Brett Zamir
To use String.concat, you need to replace your existing text, since the function does not act by reference.
要使用 String.concat,您需要替换现有文本,因为该函数不通过引用起作用。
var text ="";
for (var member in list) {
text = text.concat(list[member]);
}
Of course, the join() or += suggestions offered by others will work fine as well.
当然,其他人提供的 join() 或 += 建议也可以正常工作。
回答by sra
Simple use text = text + string2
简单使用 text = text + string2