阅读 48

常用JS函数01

这是我参与更文挑战的第10天,活动详情查看: 更文挑战

一些常用Javascript函数
  • 删除字符串中的空格
String.prototype.Trim = function()
{
  return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.LTrim = function()
{
  return this.replace(/(^\s*)/g, "");
}
String.prototype.RTrim = function()
{
  return this.replace(/(\s*$)/g, "");
}
复制代码
  • download下载方法
const download = (url, saveName,callback) =>
{
  if (typeof url === 'object' && url instanceof Blob) {
    url = URL.createObjectURL(url); // 创建blob地址
  }
  const aLink = document.createElement('a');
  aLink.href = url;
  aLink.download = saveName;
  aLink.target='_blank';
  aLink.click();
  if(callback) callback();
};
复制代码
  • object数组去重
let arrayUniqueObject = (arr, keyName) => {
  var hash = {};
  return arr.reduce(function (item, next) {
    if(!next) return ;
    hash[next[keyName]] ? '' : hash[next[keyName]] = true && item.push(next);
    return item;
  }, []);
}
复制代码
  • 日期时间格式化
let formatTime = function (time,str) {
  var date = new Date(time),
    year = date.getFullYear(),
    month = date.getMonth() + 1 ,
    day = date.getDate() ,
    hour = date.getHours(),
    minute = date.getMinutes(),
    second = date.getSeconds(),
    week = date.getDay(),
    weekdays = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];

  switch (str) {  //"YY-MM-DD-HH-MM-SS"
    case "HH:MM":
      return [hour, minute].map(formatNumber).join(':')
      break;
    case 'YY-MM-DD': //2000-01-01
      return [year, month, day].map(formatNumber).join('-')
      break;
    case 'MM-DD-ss': //01-01
      if(time === formatTime((new Date().getTime()),'YY-MM-DD')){
        return '今天';
      }else if(time === formatTime((new Date().getTime())+(1000*60*60*24),'YY-MM-DD')){
        return '明天';
      }else {
        return [ month, day].map(formatNumber).join('-')
      }

      break;
    case 'MM-DD': //2000-01-01
      return [ month, day].map(formatNumber).join('-')
      break;
    case 'HH:MM': //2000-01-01
      return [hour, minute].map(formatNumber).join(':')
      break;
    case 'YY.MM.DD HH:MM': // 2000.01.01 02:06
      return [year, month, day].map(formatNumber).join('.') + ' ' + [hour, minute].map(formatNumber).join(':')
      break;
    case 'YY-MM-DD HH:MM': // 2000-01-01 02:06
      return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
      break;
    case 'YY-MM-DD HH:MM:SS': // 2000-01-01 02:06
      return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute,second].map(formatNumber).join(':')
      break;
    case "YY.MM.DD": // 2000.01.01
      return [year, month, day].map(formatNumber).join('.')
      break;
    case "objeact":
      return  {
        year :year ,
        month:month,
        day :day ,
        hour :hour ,
        minute:minute,
        second:second,
        week :week === 0 ?7:week ,
        getDay :week,
        weekValue:weekdays[week]
      }
      break;
    default:
      return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  }
}
复制代码
  • html转解码
    var HtmlUtil = {
      /*1.用浏览器内部转换器实现html转码*/
      htmlEncode:function (html){
        //1.首先动态创建一个容器标签元素,如DIV
        var temp = document.createElement ("div");
        //2.然后将要转换的字符串设置为这个元素的innerText(ie支持)或者textContent(火狐,google支持)
        (temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html);
        //3.最后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串了
        var output = temp.innerHTML;
        temp = null;
        return output;
      },
      /*2.用浏览器内部转换器实现html解码*/
      htmlDecode:function (text){
        //1.首先动态创建一个容器标签元素,如DIV
        var temp = document.createElement("div");
        //2.然后将要转换的字符串设置为这个元素的innerHTML(ie,火狐,google都支持)
        temp.innerHTML = text;
        //3.最后返回这个元素的innerText(ie支持)或者textContent(火狐,google支持),即得到经过HTML解码的字符串了。
        var output = temp.innerText || temp.textContent;
        temp = null;
        return output;
      },
      /*3.用正则表达式实现html转码*/
      htmlEncodeByRegExp:function (str){
        var s = "";
        if(str.length == 0) return "";
        s = str.replace(/&/g,"&");
        s = s.replace(/</g,"&lt;");
        s = s.replace(/>/g,"&gt;");
        s = s.replace(/ /g,"&nbsp;");
        s = s.replace(/\'/g,"&#39;");
        s = s.replace(/\"/g,"&quot;");
        return s;
      },
      /*4.用正则表达式实现html解码*/
      htmlDecodeByRegExp:function (str){
        var s = "";
        if(str.length == 0) return "";
        s = str.replace(/&amp;/g,"&");
        s = s.replace(/\r?\n/g,"<br />");
        s = s.replace(/&lt;/g,"<");
        s = s.replace(/&gt;/g,">");
        s = s.replace(/&nbsp;/g," ");
        s = s.replace(/&#39;/g,"\'");
        s = s.replace(/&quot;/g,"\"");
        return s;
      }
    };
复制代码
  • 笛卡尔积(适用于商品规格等)
    • 笛卡尔乘积是指在数学中,两个集合X和Y的笛卡尓积,又称直积,表示为X × Y,第一个对象是X的成员而第二个对象是Y的所有可能有序对的其中一个成员 。
    • 假设集合A={a, b},集合B={0, 1, 2},则两个集合的笛卡尔积为{(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}。
    function cartesian(arr) {
        if (arr.length < 2) return arr[0] || [];
        return [].reduce.call(arr, function (col, set) {
            let res = [];
            col.forEach(c => {
                set.forEach(s => {
                    let t = [].concat(Array.isArray(c) ? c : [c]);
                    t.push(s);
                    res.push(t);
                })
            });
            return res;
        });
    }
    
    
    function discarts() {
          //笛卡尔积
          var twodDscartes = function (a, b) {
            var ret = [];
            for (var i = 0; i < a.length; i++) {
              for (var j = 0; j < b.length; j++) {
                ret.push(ft(a[i], b[j]));
              }
            }
            return ret;
          }
          var ft = function (a, b) {
            if (!(a instanceof Array))
              a = [a];
            var ret = a.slice(0);
            ret.push(b);
            return ret;
          }
          //多个一起做笛卡尔积
          return (function (data) {
            var len = data.length;
            if (len == 0)
              return [];
            else if (len == 1)
              return data[0];
            else {
              var r = data[0];
              for (var i = 1; i < len; i++) {
                r = twodDscartes(r, data[i]);
              }
              return r;
            }
          })(arguments.length > 1 ? arguments : arguments[0]);
}
    
复制代码
  • 以上所述是给大家介绍的详解JS的递归函数,希望对大家有所帮助
文章分类
前端
文章标签