JavaScript中常用函数集合

说明

我们都知道函数在JavaScript中的地位是非常重要的,函数式编程是这门语言的精髓,本文不会在这里针对函数去展开,后面我会详细介绍JavaScript的函数式编程的一些概念,这里主要是收集一些我们平时常用到的函数,如果能熟练应用的话会对你的编程速度有很大的提高。希望能帮助到更多的人:)

常用函数集合

  1. 将类数组对象转换为真数组

    1
    2
    3
    function arrayify(a){
    return [].slice.call(a);
    }
  2. 判断是否移动设备访问

    1
    2
    3
    4
    5
    6
    7
    8
    //first
    var ua = navigator.userAgent.toLowerCase(),
    isMobile = ua.search( /(iphone)|(ipod)|(android)/ ) === -1; //false是移动设备,true不是
    //second
    function isMobileUserAgent(){
    var ua = navigator.userAgent.toLowerCase();
    return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(ua));
    }
  3. 获取当前路径

    1
    2
    var currentUrl = document.location.toString().toLowerCase()||this.href.toString().toLowerCase();
    //这种情况其实就是if else 的一种简写表示当对象存在为true的时候给它后面的值 如果对象不存在为false的时候给它前面的默认值
  4. 字符串长度截取

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    function cutstr(str, len) {
    var temp,
    icount = 0,
    patrn = /[^\x00-\xff]/
    strre = "";
    for (var i = 0; i < str.length; i++) {
    if (icount < len - 1) {
    temp = str.substr(i, 1);
    if (patrn.exec(temp) == null) {
    icount = icount + 1
    } else {
    icount = icount + 2
    }
    strre += temp
    } else {
    break;
    }
    }
    return strre + "..."
    }
  5. 替换全部

    1
    2
    3
    String.prototype.replaceAll = function(s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2)
    }
  6. 清除空格

    1
    2
    3
    4
    5
    6
    String.prototype.trim = function() {
    var reExtraSpace = /^\s*(.*?)\s+$/;
    return this.replace(reExtraSpace, "$1")
    }
    function ltrim(s){ return s.replace( /^(\s*| *)/, ""); } //清除左空格
    function rtrim(s){ return s.replace( /(\s*| *)$/, ""); } //清除右空格
  7. 判断是否以某个字符串开头,结束

    1
    2
    3
    4
    5
    6
    7
    String.prototype.startWith = function (s) {
    return this.indexOf(s) == 0
    }//开头
    String.prototype.endWith = function (s) {
    var d = this.length - s.length;
    return (d >= 0 && this.lastIndexOf(s) == d)
    } //结束
  8. 转义html标签

    1
    2
    3
    function HtmlEncode(text) {
    return text.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>')
    }
  9. 判断是否为数字类型

    1
    2
    3
    4
    5
    6
    7
    8
    function isDigit(value) {
    var patrn = /^[0-9]*$/;
    if (patrn.exec(value) == null || value == "") {
    return false
    } else {
    return true
    }
    }
  10. 设置cookie值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function setCookie(name, value, Hours) {
    var d = new Date();
    var offset = 8;
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    var nd = utc + (3600000 * offset);
    var exp = new Date(nd);
    exp.setTime(exp.getTime() + Hours * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString() + ";domain=www.163.com;"
    }
  11. 获取cookie值

    1
    2
    3
    4
    5
    function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]);
    return null
    }
  12. 加载样式文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    function LoadStyle(url) {
    try {
    document.createStyleSheet(url)
    } catch(e) {
    var cssLink = document.createElement('link');
    cssLink.rel = 'stylesheet';
    cssLink.type = 'text/css';
    cssLink.href = url;
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(cssLink)
    }
    }
  13. 返回脚本

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    function evalscript(s) {
    if(s.indexOf('<script') == -1) return s;
    var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig;
    var arr = [];
    while(arr = p.exec(s)) {
    var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;
    var arr1 = [];
    arr1 = p1.exec(arr[0]);
    if(arr1) {
    appendscript(arr1[1], '', arr1[2], arr1[3]);
    } else {
    p1 = /<script(.*?)>([^\x00]+?)<\/script>/i;
    arr1 = p1.exec(arr[0]);
    appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1);
    }
    }
    return s;
    }
  14. 清除脚本

    1
    2
    3
    function stripscript(s) {
    return s.replace(/<script.*?>.*?<\/script>/ig, '');
    }
  15. 动态加载脚本

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    function appendscript(src, text, reload, charset) {
    var id = hash(src + text);
    if(!reload && in_array(id, evalscripts)) return;
    if(reload && $(id)) {
    $(id).parentNode.removeChild($(id));
    }

    evalscripts.push(id);
    var scriptNode = document.createElement("script");
    scriptNode.type = "text/javascript";
    scriptNode.id = id;
    scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset);
    try {
    if(src) {
    scriptNode.src = src;
    scriptNode.onloadDone = false;
    scriptNode.onload = function () {
    scriptNode.onloadDone = true;
    JSLOADED[src] = 1;
    };
    scriptNode.onreadystatechange = function () {
    if((scriptNode.readyState == 'loaded' || scriptNode.readyState == 'complete') && !scriptNode.onloadDone) {
    scriptNode.onloadDone = true;
    JSLOADED[src] = 1;
    }
    };
    } else if(text){
    scriptNode.text = text;
    }
    document.getElementsByTagName('head')[0].appendChild(scriptNode);
    } catch(e) {}
    }
  16. 返回按ID检索的元素对象

    1
    2
    3
    function $(id) {
    return !id ? null : document.getElementById(id);
    }
  17. 跨浏览器绑定事件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    function addEventSamp(obj,evt,fn){ 
    if(!oTarget){return;}
    if (obj.addEventListener) {
    obj.addEventListener(evt, fn, false);
    }else if(obj.attachEvent){
    obj.attachEvent('on'+evt,fn);
    }else{
    oTarget["on" + sEvtType] = fn;
    }
    }
  18. 跨浏览器删除事件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    function delEvt(obj,evt,fn){
    if(!obj){return;}
    if(obj.addEventListener){
    obj.addEventListener(evt,fn,false);
    }else if(oTarget.attachEvent){
    obj.attachEvent("on" + evt,fn);
    }else{
    obj["on" + evt] = fn;
    }
    }
  19. 为元素添加on方法

    1
    2
    3
    4
    5
    6
    7
    8
    Element.prototype.on = Element.prototype.addEventListener;

    NodeList.prototype.on = function (event, fn) {、
    []['forEach'].call(this, function (el) {
    el.on(event, fn);
    });
    return this;
    };
  20. 为元素添加trigger方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    Element.prototype.trigger = function (type, data) {
    var event = document.createEvent('HTMLEvents');
    event.initEvent(type, true, true);
    event.data = data || {};
    event.eventName = type;
    event.target = this;
    this.dispatchEvent(event);
    return this;
    };
    NodeList.prototype.trigger = function (event) {
    []['forEach'].call(this, function (el) {
    el['trigger'](event);
    });
    return this;
    };
  21. getElementsByClassName

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    function getElementsByClassName(name) {
    var tags = document.getElementsByTagName('*') || document.all;
    var els = [];
    for (var i = 0; i < tags.length; i++) {
    if (tags.className) {
    var cs = tags.className.split(' ');
    for (var j = 0; j < cs.length; j++) {
    if (name == cs[j]) {
    els.push(tags);
    break
    }
    }
    }
    }
    return els
    }
  22. 获取页面高度

    1
    2
    3
    4
    5
    6
    function getPageHeight(){
    var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat"
    ? a
    : g.documentElement;
    return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight);
    }
  23. 获取页面scrollLeft

    1
    2
    3
    4
    function getPageScrollLeft(){
    var a = document;
    return a.documentElement.scrollLeft || a.body.scrollLeft;
    }
  24. 获取页面可视宽度

    1
    2
    3
    4
    5
    6
    function getPageViewWidth(){
    var d = document, a = d.compatMode == "BackCompat"
    ? d.body
    : d.documentElement;
    return a.clientWidth;
    }
  25. 获取页面宽度

    1
    2
    3
    4
    5
    6
    function getPageWidth(){
    var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat"
    ? a
    : g.documentElement;
    return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
    }
  26. 获取页面scrollTop

    1
    2
    3
    4
    function getPageScrollTop(){
    var a = document;
    return a.documentElement.scrollTop || a.body.scrollTop;
    }
  27. 获取页面可视高度

    1
    2
    3
    4
    5
    6
    function getPageViewHeight() {
    var d = document, a = d.compatMode == "BackCompat"
    ? d.body
    : d.documentElement;
    return a.clientHeight;
    }
  28. 获取窗体可见范围的宽与高

    1
    2
    3
    4
    5
    6
    7
    function getViewSize(){
    var de=document.documentElement;
    var db=document.body;
    var viewW=de.clientWidth==0 ? db.clientWidth : de.clientWidth;
    var viewH=de.clientHeight==0 ? db.clientHeight : de.clientHeight;
    return Array(viewW ,viewH);
    }
  29. 去掉url前缀

    1
    2
    3
    4
    5
    6
    7
    function removeUrlPrefix(a){
    a=a.replace(/:/g,":").replace(/./g,".").replace(///g,"/");
    while(trim(a).toLowerCase().indexOf("http://")==0){
    a=trim(a.replace(/http:\/\//i,""));
    }
    return a;
    }
  30. 断鼠标是否移出事件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    function isMouseOut(e, handler) {
    if (e.type !== 'mouseout') {
    return false;
    }
    var reltg = e.relatedTarget ? e.relatedTarget : e.type === 'mouseout' ? e.toElement : e.fromElement;
    while (reltg && reltg !== handler) {
    reltg = reltg.parentNode;
    }
    return (reltg !== handler);
    }
  31. 获得URL中GET参数值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function get_get(){ 
    querystr = window.location.href.split("?")
    if(querystr[1]){
    GETs = querystr[1].split("&");
    GET = [];
    for(i=0;i<GETs.length;i++){
    tmp_arr = GETs.split("=")
    key=tmp_arr[0]
    GET[key] = tmp_arr[1]
    }
    }
    return querystr[1];
    }
  32. 清除相同的数组

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    String.prototype.unique=function(){
    var x=this.split(/[\r\n]+/);
    var y='';
    for(var i=0;i<x.length;i++){
    if(!new RegExp("^"+x.replace(/([^\w])/ig,"\\$1")+"$","igm").test(y)){
    y+=x+"\r\n"
    }
    }
    return y
    };
  33. 按字母排序,对每行进行数组排序

    1
    2
    3
    4
    5
    function SetSort(){
    var text=K1.value.split(/[\r\n]/).sort().join("\r\n");//顺序
    var test=K1.value.split(/[\r\n]/).sort().reverse().join("\r\n");//反序
    K1.value=K1.value!=text?text:test;
    }
  34. 字符串反序

    1
    2
    3
    function isReverse(text){
    return text.split('').reverse().join('');
    }
  35. 清除html代码中的脚本

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function clear_script(){
    K1.value=K1.value.replace(/<script.*?>[\s\S]*?<\/script>|\s+on[a-zA-Z]{3,16}\s?=\s?"[\s\S]*?"|\s+on[a-zA-Z]{3,16}\s?=\s?'[\s\S]*?'|\s+on[a-zA-Z]{3,16}\s?=[^ >]+/ig,"");
    }
    //动态执行JavaScript脚本
    function javascript(){
    try{
    eval(K1.value);
    }catch(e){
    alert(e.message);
    }
    }
  36. 实现base64解码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    function base64_decode(data){
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,ac = 0,dec = "",tmp_arr = [];
    if (!data) { return data; }
    data += '';
    do {
    h1 = b64.indexOf(data.charAt(i++));
    h2 = b64.indexOf(data.charAt(i++));
    h3 = b64.indexOf(data.charAt(i++));
    h4 = b64.indexOf(data.charAt(i++));
    bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
    o1 = bits >> 16 & 0xff;
    o2 = bits >> 8 & 0xff;
    o3 = bits & 0xff;
    if (h3 == 64) {
    tmp_arr[ac++] = String.fromCharCode(o1);
    } else if (h4 == 64) {
    tmp_arr[ac++] = String.fromCharCode(o1, o2);
    } else {
    tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
    }
    } while (i < data.length);
    dec = tmp_arr.join('');
    dec = utf8_decode(dec);
    return dec;
    }
  37. 实现utf8解码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    function utf8_decode(str_data){
    var tmp_arr = [],i = 0,ac = 0,c1 = 0,c2 = 0,c3 = 0;str_data += '';
    while (i < str_data.length) {
    c1 = str_data.charCodeAt(i);
    if (c1 < 128) {
    tmp_arr[ac++] = String.fromCharCode(c1);
    i++;
    } else if (c1 > 191 && c1 < 224) {
    c2 = str_data.charCodeAt(i + 1);
    tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
    i += 2;
    } else {
    c2 = str_data.charCodeAt(i + 1);
    c3 = str_data.charCodeAt(i + 2);
    tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
    i += 3;
    }
    }
    return tmp_arr.join('');
    }
  38. 随机数时间戳

    1
    2
    3
    4
    function uniqueId(){
    var a=Math.random,b=parseInt;
    return Number(new Date()).toString()+b(10*a())+b(10*a())+b(10*a());
    }
  39. 获取网页被卷去的位置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function getScrollXY() {
    return document.body.scrollTop ? {
    x: document.body.scrollLeft,
    y: document.body.scrollTop
    }: {
    x: document.documentElement.scrollLeft,
    y: document.documentElement.scrollTop
    }
    }
  40. 检验URL链接是否有效

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    function getUrlState(URL){ 
    var xmlhttp = new ActiveXObject("microsoft.xmlhttp");
    xmlhttp.Open("GET",URL, false);
    try{
    xmlhttp.Send();
    }catch(e){
    }finally{
    var result = xmlhttp.responseText;
    if(result){
    if(xmlhttp.Status==200){
    return(true);
    }else{
    return(false);
    }
    }else{
    return(false);
    }
    }
    }
  41. 获取URL中的参数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var GLOBLE_PARAMS = (function () {
    var args = new Object();
    var query = location.search.substring(1);
    var pairs = query.split("&"); // Break at ampersand
    for(var i = 0; i < pairs.length; i++) {
    var pos = pairs[i].indexOf('=');
    if (pos == -1) continue;
    var argname = pairs[i].substring(0,pos);
    var value = pairs[i].substring(pos+1);
    value = decodeURIComponent(value);
    args[argname] = value;
    }
    return args;
    })();
  42. 数组扁平化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    //[1, [2, [ [3, 4], 5], 6]] => [1, 2, 3, 4, 5, 6]
    function flatten(arr){
    var i,ret=[], len = arr.length;
    for(i=0;i<len;i++){
    if(Array.isArray(arr[i])){
    ret = ret.concat(flatten(arr[i]))
    }else{
    ret.push(arr[i])
    }

    }
    return ret
    }
  43. 字符串驼峰化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    /**
    * Camelize a string, cutting the string by multiple
    separators like
    * hyphens, underscores and spaces.
    *
    * @param {text} string Text to camelize
    * @return string Camelized text
    */
    function camelize(text) {
    return text.replace(/^([A-Z])|[\s-_]+(\w)/g, function(match, p1, p2, offset) {
    if (p2) return p2.toUpperCase();
    return p1.toLowerCase();
    });
    }

    camelize("some_database_field_name")// someDatabaseFieldName;
    camelize("Some label that needs to be camelized")// someLabelThatNeedsToBeCamelized;
    camelize("some-javascript-property")// someJavascriptProperty;
    camelize("some-mixed_string with spaces_underscores-and-hyphens");
    // someMixedStringWithSpacesUnderscoresAndHyphens
  44. 字符串反驼峰化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    /**
    * Decamelizes a string with/without a custom separator (underscore by default).
    *
    * @param str String in camelcase
    * @param separator Separator for the new decamelized string.
    */
    function decamelize(str, separator){
    separator = typeof separator === 'undefined' ? '_' : separator;
    return str
    .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
    .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
    .toLowerCase();
    }
    // decamelize("someDatabaseFieldName", " ")->'some database field name';
    // decamelize("someLabelThatNeedsToBeCamelized", "-")->'some-label-that-needs-to-be-camelized';
    // decamelize("someJavascriptProperty", "_") -> 'some_javascript_property';