Home > Web Front-end > JS Tutorial > body text

JavaScript Study Notes 2 String Splicing_Basic Knowledge

WBOY
Release: 2016-05-16 18:31:15
Original
1001 people have browsed it

var str="hello";
str ="world";
In fact, the steps performed by this code behind the scenes are as follows:
(1) Create a string to store "hello".
(2) Create a string to store "world".
(3) Create a string to store the connection result.
(4) Copy the current content of str to the result.
(5) Copy "world" into the result.
(6) Update str so that it points to the result.
Steps 2 to 6 will be executed every time string concatenation is completed, making this operation very resource-consuming. If this process is repeated hundreds, or even thousands, of times, it can cause performance problems. The solution is to use an Array object to store the string, and then use the join() method (the parameter is an empty string) to create the final string. Imagine replacing the previous code with the following code:

Copy the code The code is as follows:

var str =new Array();
str[0]="hello";
str[1]="world";
str.join("");

This way, no matter how many strings are introduced into the array, it won't be a problem because the join operation only occurs when the join() method is called. At this point, the steps are as follows:
(1) Create a string to store the result.
(2) Copy each string to the appropriate location in the result.
Copy code The code is as follows:

function StringBuilder(){
this._string= new Array();
}
StringBuilder.prototype.Append=function(str){
this._string.push(str);
}
StringBuilder.prototype.toString=function( ){
return this._string.join("");
}

Related articles to improve efficiency:
The fastest way to splice html array strings

StringBuffer class for connecting large strings in JavaScript

For more information, please refer to previous articles of Script House.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template