Friends who have had relevant experience know that the efficiency of Jscript is limited after all. If you use conventional algorithms to find data in an array, it will be very slow to execute.
For example, in a data array containing 500 strings, we want to find a specified character (key) and return its array subscript. If we use this algorithm:
[Copy to clipboard]CODE :
function usual_search(data,key)
{
var m=data.length
for(i=0;i
}
Due to the need to do multiple comparisons, the operation will be quite slow.
What this topic will introduce is a method that makes full use of Jscript's built-in methods to find data in an array. With the help of Jscript's built-in methods, its efficiency is much better than the above conventional algorithm. For the sake of (humor | bluffing), I named it "JS violent search method".
This search method has a requirement for array elements: the content of the array elements must not contain half-width commas (,) and one of the substitution symbols we specify (for example, in the following example, we specify the substitution symbol as a tab character "┢"). Pay attention to meeting this requirement when constructing and maintaining the array in advance.
The idea of JS tyrannical search method is very simple. There is only one principle, which is to "make full use of Jscript's built-in methods":
We first use the toString() method of the Array object to generate a string containing array elements. In this string, each array element is separated by a half-width comma (,), so we require in advance that the content of the array element must not contain a half-width comma.
We then use the replace() method of the String object to replace the key string we are looking for contained in this string with a special symbol (substitution symbol) we specify. Generally, we choose an uncommon character. As a substitution symbol, in the following example I use a tab character (┢). Any symbol that can ensure that it will not appear in an array element can be used as a substitution symbol.
Next is our most brutal step, which is to use the replace() method to remove all characters except half-width commas (,) and substitution symbols (┢). After cleaning everything, the string becomes a string of half-width commas containing a substitution symbol (this looks like:,,,,,,,,,,,,,,,,,┢,,,,,, ,,,).
Finally, use the indexOf() method of the String object to return the position of the substitution symbol in the string, and this position is exactly the array subscript in the original array.
Jscript sample program