JS中常用的封装方法大全(函数封装)

1. 封装 indexOf() 方法

    var arr = ['a', 'b', 'c', 'd', 'e', 'f']
    function getIndexof(brr, inme) {
        for (var i = 0; i < brr.length; i++) {
            if (brr[i] == inme) {
                return i
            }
        }
        return -1
    }
    console.log(getIndexof(arr, 'd'))     输出:3          //找到返回下标
    console.log(getIndexof(arr, 'k'))     输出:-1         //找不到返回-1

2. 封装 reverse() 方法 - 翻转

   var arr = [1, 2, 3, 4, 5, 6]
    function getReverse(brr) {
        var newarr = []
        for (var i = 0; i < brr.length; i++) {
            newarr.unshift(brr[i])
        }
        return newarr
    }
    console.log(getReverse(arr))
输出: [6, 5, 4, 3, 2, 1]

3. 封装 trim() 方法 把前后两边的空格去掉

     var arr = '  a  b  c  '
    function getTrim(brr) {
        var a = brr.replace(/^\s+|\s+$/g, '')
        return a
    }
    console.log(getTrim(arr))
输出:a  b  c       //前后没有空格

4. 封装随机4位不重复密码

        function getTime(n) {
        var arr = []
        while (arr.length < n) {
            var num = Math.floor(Math.random() * 10)  //取随机数
            if (arr.indexOf(num) == -1) {   //去重
                arr.push(num)
            }
        }
        return arr.join('')
    }
    console.log(getTime(4))
输出:   4190   // 随机出现4位不一样的数字

5. 封装字符串转对象的方法

        var str = '?name=张三 & num=18 & sum=110'
        function getStr(crr) {
        var arr = str.replace('?', '')
        var brr = arr.split('&')
        var obj = {}
        for (var i in brr) {
            obj[brr[i].split('=')[0]] = brr[i].split('=')[1]
        }
        return obj
    }
    console.log(getStr(str))
输出: {name: "张三 ", " num": "18 ", " sum": "110"}

6. 封装字符串中出现最多的项,并得到对应的数量

        var arr = 'aaaaaaaasssssddddffdsdfksk'
        function getName(list) {
        var obj = {}, num = 0, time = 0
        for (var i in list) {
            obj[list[i]] ? obj[list[i]] += 1 : obj[list[i]] = 1
        }
        for (var i in obj) {
            if (obj[i] > num) {
                num = obj[i]
                time = i
            }
        }
        return obj
    }
    console.log(getName(arr))
输出:{a: 8, s: 7, d: 6, f: 3, k: 2}
//--------------------------------------------
    var arr = 'aasssssdddssddddddfssdf'
    function getNa(list) {
    var obj = {}, name = 0, time = 0
    for (var i in list) {
        obj[list[i]] = obj[list[i]] ? obj[list[i]] + 1 : 1
    }
    for (var i in obj) {
        if (name < obj[i]) {
            name = obj[i]
            time = i
        }
    }
    return `${time}出现的次数最多,出现了${name}次`
}
console.log(getNa(arr))
输出:d出现的次数最多,出现了10次

7. 封装转驼峰方法,首字母大写

var arr = 'get-elements-byclass-name'
function getNod(brr) {
    var con = brr.split('-')
    var str = con[0]
    for (let i = 1; i < con.length; i++) {
        str += con[i][0].toUpperCase() + con[i].slice(1)
    }
    return str
}
console.log(getNod(arr))
输出:getElementsByclassName

你可能感兴趣的:(JS中常用的封装方法大全(函数封装))