Home >Web Front-end >JS Tutorial >Commonly used array string methods

Commonly used array string methods

php中世界最好的语言
php中世界最好的语言Original
2018-03-09 16:11:161768browse

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 = &#39;abcdefghijklmnopqrstuvwxyz0123456789&#39;;    var tmp = &#39;&#39;;    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 = &#39;&#39;,
        maxValue = 1;    for(var k in charObj) {        if(charObj[k] >= maxValue) {
            maxChar = k;
            maxValue = charObj[k];
        }
    }    return maxChar + &#39;:&#39; + 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!

Statement:
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