我有一些Java的经验,我知道字符串与“+”操作符连接会产生新的对象。
我想知道如何以最好的方式在JS中做它,它的最佳实践是什么?
我有一些Java的经验,我知道字符串与“+”操作符连接会产生新的对象。
我想知道如何以最好的方式在JS中做它,它的最佳实践是什么?
当前回答
您可以尝试使用此代码(相同情况)
chaine1 + chaine2;
我建议你也用(我更喜欢这个)绳子。concat方法
其他回答
曾经有一段时间,将字符串添加到数组中并使用join来结束字符串是最快/最好的方法。现在浏览器有高度优化的字符串例程,建议使用+和+=方法是最快/最好的
您可以尝试使用此代码(相同情况)
chaine1 + chaine2;
我建议你也用(我更喜欢这个)绳子。concat方法
在JS中,“+”连接通过创建一个新的String对象来工作。
例如,用……
var s = "Hello";
...我们有一个物体s。
下一个:
s = s + " World";
s是一个新对象。
方法2: String.prototype.concat
MDN对string.concat()有如下说明:
强烈建议使用字符串连接操作符 (+, +=)而不是此方法的性能原因
也可以查看@Bergi的链接。
We can't concatenate a string variable to an integer variable using concat() function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator. As we know, functions are pretty slower than operators. functions needs to pass values to the predefined functions and need to gather the results of the functions. which is slower than doing operations using operators because operators performs operations in-line but, functions used to jump to appropriate memory locations... So, As mentioned in previous answers the other difference is obviously the speed of operation.
< !DOCTYPE html > < html > 身体< > concat()方法连接两个或多个字符串</p> < p id = "演示" > < / p > < p id = " demo1 " > < / p > <脚本> Var text1 = 4; var text2 = "World!"; . getelementbyid(“演示”)。innerHTML = text1 + text2; //下面的线不能产生结果 . getelementbyid(“demo1”)。innerHTML = text1.concat(text2); > < /脚本 <p><strong> Concat()方法不能将字符串与</strong></p> 身体< / > < / html >