Home >Web Front-end >JS Tutorial >Common uses of javascript arrays and strings
Arrays and Strings in js are very simple to understand, but some common usages are complicated and difficult to remember and can be easily confused. I summarized the usage of js arrays and js strings and explained the differences. Students who are not familiar with it can learn from it and have a look!
First of all, we have to know that strings and arrays can be converted to each other.
Convert the array into a string
The input effect is as follows:
The output at this time is the same as directly using The alert output array arr has the same effect. What if we want them to form something similar to English words?
You only need to write var str = arr.join(); in the code shown in Figure 1 as var str = arr.join("");
The output effect is as follows:
What if we want a colon between the two letters abc? It's very simple. Write var str = arr.join(); as var str = arr.join(":");
The effect is as follows: ~
In summary, if join( ) When there are parameters in the brackets, the elements in the array converted into strings will be separated by the parameters. The default is to use commas.
Convert string to array
Use split();
If the brackets have quotes, the string will be decomposed into an array with a single character as an element. The code and effects are shown in the figure below.
If there are quotation marks within the brackets, and there is a space within the quotation marks. The effect is as follows:
If you write var strArr = str.split('lo');
Through the above phenomenon, we can conclude Conclusion: The parameter in split() is part of str, which will split the string and become one of the array elements. None of these elements contain the parameter.
slice()
var str = "hello world";var strArr = str.slice(2,5); //截取字符串中第2位到第5位的字符。包括第2位,不包括第5位; alert(strArr);
substring(beginIndex, endIndex) usage is the same as slice()
arr.push()
Add elements to arr, and the added elements will be ranked last.
arr.pop()
Delete The last element of the array
arr.slice(beginIndex,endIndex )
Intercept the elements in the array, excluding the last digit.
arr.splice(beginIndex,length,[item1,item2,item3...])
Delete the length element starting from the subscript beginIndex in the arr array, and Add elements item1, item2, item3... starting from beginIndex at a time.
Related recommendations:
JavaScript array-String-MathFunction
The above is the detailed content of Common uses of javascript arrays and strings. For more information, please follow other related articles on the PHP Chinese website!