string concatenation in JS is often encountered, sometimes encountered long string stitching will be more trouble. such as HTML strings;
The code is as follows |
Copy Code |
var str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
var str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; |
The editor has a limited width and, for degree of readability, the string must be wrapped. But if you do it directly like this, you will have a direct error.
The code is as follows |
Copy Code |
var str = "Aaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa AAAAAAAAAAAAAAAAAAAAAA "; var str =" Aaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa "; |
At this point, you need to splice the string, the most basic method:
The code is as follows |
Copy Code |
var str = "AAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAA"; var str = "AAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAA"; |
If only two or three lines that is fine, to have a dozens of line, not only time-consuming and laborious, but also easy to make mistakes.
string concatenation techniques, using arrays for character stitching:
The code is as follows |
Copy Code |
var strarr = []; Strarr.push ("aaaaaaaaaaaaaaaaaa"); Strarr.push ("aaaaaaaaaaaaaaaaaaaaaa"); Strarr.push ("aaaaaaaaaaaaaaaaaaaaaaa"); Strarr.join (""); var strarr = []; Strarr.push ("aaaaaaaaaaaaaaaaaa"); Strarr.push ("aaaaaaaaaaaaaaaaaaaaaa"); Strarr.push ("aaaaaaaaaaaaaaaaaaaaaaa"); Strarr.join (""); |
This method reduces the probability of error, but the amount of work is still not small.
A more convenient method for string concatenation:
Wrapping directly in a string produces an error, but if you add a backslash "" to the back of each line, it will not produce an error;
The code is as follows |
Copy Code |
var str = "Aaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaaa "; The last line does not need to add a backslash var str = "Aaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaaa ";
|
The last line does not need to add a backslash of course, this method also has a disadvantage, that is, each row can not be followed by a single-line comment.
As for the performance comparison between these methods, I do not think much of the consideration, unless there are thousands of lines of string concatenation, otherwise the performance gap can be negligible; the readability of the program should be in the front.