js常用函数

2020-11-12  本文已影响0人  Jey
js替换字符串
// str原字符串,reStr需要替换的字符串,toStr替换成的字符串
function(str, reStr, toStr) {
    let s = new RegExp(reStr,'g')
    return str.replace(s, toStr);
}
js热更新对比版本号
function compareVersion(curV, newV) {
    let curVArr = curV.toString().split('.')
    let newVArr = newV.toString().split('.')
    let minLength = Math.min(curVArr.length, newVArr.length)
    let pos = 0 // 每一个.分开的位置
    let diff = 0
    let hasNewVersion = false;
    while (pos < minLength) {
        diff = parseInt(newVArr[pos]) - parseInt(curVArr[pos])
        if (diff != 0) {
            hasNewVersion = diff > 0? true: false
            break;
        }
        pos++
    }
    // 1.0.3 与1.0.3.4的情况
    if (diff === 0 && curVArr.length < newVArr.length) {
        hasNewVersion = true;
    }
    return hasNewVersion;
}
深拷贝
function deepCopy(obj) {
    var result, oClass = getClass(obj);

    if (oClass == "Object") result = {}; //判断传入的如果是对象,继续遍历
    else if (oClass == "Array") result = []; //判断传入的如果是数组,继续遍历
    else return obj; //如果是基本数据类型就直接返回

    for (var i in obj) {
        var copy = obj[i];
        if (getClass(copy) == "Object") result[i] = util.deepCopy(copy); //递归方法 ,如果对象继续变量obj[i],下一级还是对象,就obj[i][i]
        else if (getClass(copy) == "Array") result[i] = util.deepCopy(copy); //递归方法 ,如果对象继续数组obj[i],下一级还是数组,就obj[i][i]
        else result[i] = copy; //基本数据类型则赋值给属性
    }

    return result;
}
上一篇下一篇

猜你喜欢

热点阅读