This time I will bring you the commonly used array string method. What are the precautions for using the array string method? The following is a practical case, let’s take a look.
1. Array operation
Array deduplication
Use the uniqueness of the key in the Object to filter
function unique(arr){ var obj = {} var data = [] for(var i in arr){ if(!obj[arr[i]]){ obj[arr[i]] = true; data.push(arr[i]); } } return data; }
The largest number in the array Difference
function getMaxProfit(arr){ var min = arr[0], max = arr[0]; for(var i=0;i<arr.length;i++){ if(arr[i]<min) min = arr[i]; if(arr[i]>max) max = arr[i]; } return max - min; }
2. String operation
Generate a random string of specified length
function randomString(n){ var str = 'abcdefghijklmnopqrstuvwxyz0123456789'; var tmp = ''; for(var i=0;i<n;i++) tmp += str.charAt(Math.round(Math.random()*str.length)); return tmp; }
Count the most frequent letters in the string (using the uniqueness of the key in the Object , use key to filter, and then count)
function findMaxDuplicateChar(str) { if(str.length == 1) { return str; } var charObj = {}; for(var i = 0; i < str.length; i++) { if(!charObj[str.charAt(i)]) { charObj[str.charAt(i)] = 1; } else { charObj[str.charAt(i)] += 1; } } var maxChar = '', maxValue = 1; for(var k in charObj) { if(charObj[k] >= maxValue) { maxChar = k; maxValue = charObj[k]; } } return maxChar + ':' + maxValue; }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Related reading:
How to filter out false, null, 0, "", undefined, and NaN values in a js array
How to modify the scroll bar style
table tr th and table tr td have too many fonts, how to use CSS to solve it
The above is the detailed content of Commonly used array string methods. For more information, please follow other related articles on the PHP Chinese website!