Home >Web Front-end >JS Tutorial >21 Javascript tips worth collecting_javascript tips
1 Convert Javascript array to CSV format
First consider the following application scenario. There is a Javscript character (or numeric) array, which now needs to be converted into a comma-delimited CSV format file. Then we can use the following tips, the code is as follows:
Output: apple,peaches,oranges,mangoes
Among them, the valueOf() method will convert the Javascript array into a comma-separated string. It should be noted that if you do not want to use commas to separate, for example, use | to separate, please use the join method, as follows:
Output: apple|peaches|oranges|mangoes
2 Convert CSV format back to Javscript array
So how to convert a CSV formatted string back to a Javascript array? You can use the split() method to separate using any specified characters. The code is as follows:
Output fruitsArray[0]: apple
3 Remove an element from the array based on index
If you need to remove an element from a Javascript array, you can use the splice method. This method will remove the nth element from the array based on the passed parameter n (calculated from the 0th position in the Javascript array) .
The final output is Apple,Ball,Dog
4 Remove the value in the array element according to the value of the element
The following technique is very practical. It is to delete elements in an array based on a given value. The code is as follows:
Of course, a better way is to use the prototype method to achieve it, as shown in the following code:
5 Dynamically call a method by specifying a string
Sometimes, it is necessary to dynamically call an existing method at runtime and pass in parameters. How to achieve this? The following code will do:
6 Generate random numbers from 1 to N
7 Capture browser closing event
We often want to prompt the user to save unsaved things when the user closes the browser. The following Javascript technique is very useful. The code is as follows:
Just write the code for the onbeforeunload() event
8 Check whether the back button is pressed
Similarly, you can check whether the user pressed the back key, the code is as follows:
9 Check whether the form data has changed
Sometimes, you need to check whether the user has modified the content of a form. You can use the following technique. If the content of the form has been modified, it will return true, and if the content of the form has not been modified, it will return false. The code is as follows: