Art*_*mis 136 javascript
我有一些Java的经验,我知道字符串连接与"+"运算符产生新的对象.
我想知道如何以最好的方式在JS中做到这一点,它的最佳实践是什么?
lak*_*tak 195
MDN有以下说法string.concat():
出于性能原因,强烈建议使用字符串连接运算符(+,+ =)代替此方法
另请参阅@Bergi链接.
Oze*_*ich 26
在JS中,"+"连接通过创建新String对象来工作.
例如,用......
var s = "Hello";
Run Code Online (Sandbox Code Playgroud)
......我们有一个对象小号.
下一个:
s = s + " World";
Run Code Online (Sandbox Code Playgroud)
现在,s是一个新对象.
第二种方法: String.prototype.concat
concat()函数将字符串变量连接到整数变量,因为此函数仅适用于字符串,而不适用于整数.但我们可以使用+运算符将字符串连接到数字(整数).<!DOCTYPE html>
<html>
<body>
<p>The concat() method joins two or more strings</p>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var text1 = 4;
var text2 = "World!";
document.getElementById("demo").innerHTML = text1 + text2;
//Below Line can't produce result
document.getElementById("demo1").innerHTML = text1.concat(text2);
</script>
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
您可以尝试使用此代码(大小写相同)
chaine1 + chaine2;
Run Code Online (Sandbox Code Playgroud)
我建议您也(我更喜欢)string.concat方法