This time I will bring you commonly used algorithms in js projects. What are the precautions for using algorithms in js projects? Here are practical cases, let’s take a look.
Array deduplication
var arr = [1,2,3,4,4,2,2,6,9,1,0];var newArr = [];var onOff = true;for(var i = 0;i<arr.length;i++){ onOff = true; for(var j = 0;j<newArr.length;j++){ if(newArr[j]==arr[i]){ onOff = false; } } if(onOff){ newArr.push(arr[i]); } }console.log(newArr)
Shuffling algorithm
function shuffle(arr) { var i = arr.length, t, j; while (i) { j = Math.floor(Math.random() * i--); t = arr[i]; arr[i] = arr[j]; arr[j] = t; } console.log(arr) }var arr = [1, 3, 5, 7, 9] shuffle(arr)
Write a function to count the most frequent characters in a string
var str = 'abcdefffdddddd';var obj={};for(var i=0;i<str.length;i++){ var t = str[i]; if(obj[t]){ obj[t]++; }else{ obj[t] = 1; } }console.log(obj);var max=0,tKey;for(key in obj){ if(obj[key] > max){ max = obj[key]; tKey = key; } }console.log(tKey)
I believe I have read it You have mastered the method in the case of this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Nuxt.js SSR permission verification use
How to use JS to achieve the simplest cross-domain
The above is the detailed content of Commonly used algorithms in js projects. For more information, please follow other related articles on the PHP Chinese website!