Javascript 常用数据处理函数集合 - 持续更新

学习 · 2022-01-12

数字取整

可用于input change 的数字输入处理
/** 数字整形 */
numInputChange(val, max) {
  // 转数字
  let transferNum = parseInt(val);
  // 小于0
  if(transferNum < 0) {
    transferNum = Math.abs(transferNum);
  } else if(transferNum === 0) {
    transferNum = 1;
  } else if(transferNum >= max) {
    transferNum = max;
  }

  return transferNum;
},

简单Ajax实现

function simpleAjax(options) {
    options = options || {};
    options.async = options.async || true;
    options.type = (options.type || 'GET').toUpperCase();
    options.dataType = (options.dataType || 'json').toUpperCase();
    options.postType = (options.postType || 'json').toUpperCase();

    var xhr, sp, params;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveObject) { //IE6及以下
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    // 参数处理  todo 这里数据最好判断下 不过这样直传obj也好
    params = (function(data) {
        var arr = [];
        for (var key in data) {
            arr.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        }
        return arr.join('&');
    })(options.data)
    // 注册事件
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            var status = xhr.status;
            if (status >= 200 && status < 300 || status == 304) {
                if (options.dataType == "JSON") {
                    options.success && options.success(JSON.parse(xhr.responseText), xhr.responseXML);
                } else {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                }
            } else {
                options.error && options.error(status);
            }
        } else {
            options.error && options.error(xhr.status);
        }
    }

    // 请求处理
    if (options.type == 'GET') {
        sp = options.url.indexOf("?") == -1 ? '?' : '&';
        xhr.open("GET", options.url + sp + params);
        xhr.send(null);
    } else if (options.type == 'POST') {
        xhr.open("POST", options.url, options.async);
        if (options.postType == 'JSON') {
            xhr.setRequestHeader("Content-Type", "application/json");
            // 直接处理JSON数据 string
            xhr.send(JSON.stringify(options.data));
        } else {
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(params);
        }
    }
}

simpleAjax({
    type: 'POST',
    url: API_URL,
    data: JSON.parse(paramsData),
    success: function(data, status, xhr) {
        __debug.print( "success:"+ JSON.stringify(data))
    }
})

数组扁平化

function flatten(arr) {
    return arr.reduce((flat, toFlatten) => {
        return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten)
    }, []).sort((a, b) => a -b).filter((value, index, array) => {
        return array.indexOf(value) === index;
    })

}

//input: arr = [1,[2,3,44,54,35,8],[34,568769,2354,89,843,24,[234,67,87,3349,97,435], 455,546],235662,27,9,0545];
//runing:  flatten(arr);
//output: [1, 2, 3, 8, 9, 24, 27, 34, 35, 44, 54, 67, 87, 89, 97, 234, 357, 435, 455, 546, 843, 2354, 3349, 235662, 568769]

正则数据替换

var tmpl = "假设这个{{word0}}来源于替换内容,很{{word1}}噢!";
var ctx = {word0: '词语', word1: '牛'};

tmpl.replace(/{{(.*?)}}/g, (match, key) => ctx[key.trim()]);

// console '假设这个词语来源于替换内容,很牛噢!'

向上取整

function upToceilNum(number){
    let bite = 0;
    if(number < 10){
        return 10;
    }
    while( number >= 10 ){
        number /= 10;
        bite += 1;
    }
    return Math.ceil(number) * Math.pow(10, bite);
}
// upToceilNum(567)
// 600
javascript 函数 集合
Theme Jasmine by Kent Liao | 桂ICP备15008025号-6