Home > Web Front-end > JS Tutorial > Commonly used algorithms in js projects

Commonly used algorithms in js projects

php中世界最好的语言
Release: 2018-06-04 14:55:36
Original
1703 people have browsed it

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)
Copy after login

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)
Copy after login

Write a function to count the most frequent characters in a string

var str = &#39;abcdefffdddddd&#39;;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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template