Some methods commonly used in project sorting out

Keywords: Javascript Firefox JSON IE

1. Judging the current browser type

function isBrower(){
   var ua = navigator.userAgent.toLowerCase();
   var isMiscro = ua.indexOf("micromessenger")>-1;//Wechat Browser
    var isChrome = ua.indexOf('chrome')>-1 && ua.indexOf('safari')>-1; //Chrome
    var isSafari = ua.indexOf('safari')>-1 && ua.indexOf('chrome')==-1; //safari browser
    var isFirefox = ua.indexOf('firefox')> -1; //Firefox Browser
    var isOpera = ua.indexOf('opera')> -1; //Opera Browser
    var isIE = ua.indexOf("compatible") > -1 && ua.indexOf("msie") > -1 && !ua.indexOf("opera") > -1; //IE browser
}

2. Judging whether Chinese is included in the string

function isHasChinese(str){
     var reg = new RegExp("[\\u4e00-\\u9FFF]","g");
     return reg.test(str);
}

3. Determining whether the object is empty

function isNull(data){
     return ( (data == "" || data == "undefined" || data ==         undefined) ? true :false);
}

4. Construct a string of IDS in an array and connect them with @.

strIds =  item.data.map(function(ditem){
    return  ditem.tableId
}).join("@");

5. Using el-tooltip components

<span class="text2" @mouseenter="showTooltip($event)"
@mouseleave="hiddenTooltip($event)">{{item.frequency1}}</span>

<el-tooltip ref="textTooltip" effect="light" :content="textTooltipContent" placement="top-start"></el-tooltip>
showTooltip: function (event) {
  var ev = event || window.event;
  var eventName = ev.target.className;
  if (eventName.indexOf('text') != -1) {
    if (ev.target.offsetWidth < ev.target.scrollWidth) {
      var tooltip = this.$refs.textTooltip;
      this.textTooltipContent = ev.target.innerText;
      tooltip.referenceElm = ev.target;
      tooltip.$refs.popper.style.display = 'none';
      tooltip.doDestroy();
      tooltip.setExpectedState(true);
      tooltip.handleShowPopper();
    }
  }
},
hiddenTooltip: function () {
  const tooltip = this.$refs.textTooltip;
  if (tooltip) {
    tooltip.setExpectedState(false);
    tooltip.handleClosePopper();
  }
}

6. Scroll bars are positioned at positions with color display

getTableBody: function (tab) {
  if (!tab || tab.name != 'nav1' && tab.name != 'nav3') {
    var _this = this;
    setTimeout(function () {
      _this.curTopHeight.forEach(function (e, index) {
        var elTable = document.getElementsByClassName('el-table__body-wrapper')[index];
        if (elTable) {
          var td = elTable.getElementsByClassName('cell')[0];
          var tdWindth = parseInt(td.style.width) * e.left;
          document.getElementsByClassName('el-table__body-wrapper')[index].scrollTop = e.height;
          document.getElementsByClassName('el-table__body-wrapper')[index].scrollLeft = tdWindth;
        }
      })
    }, 1200);
  }
}

// Find the colored data in the table

findColorText: function (data) {
  var height = 24;
  var left = 0;
  var _this = this;
  if (data && data.length) {
    var stop = true;
    data.forEach(function (item, index) {
      if (stop) {
        var _index = index;
        for (var i in item) {
          if (item[i].indexOf('color') != -1) {
            height = _index * height;
            left = i.replace('column_key', '');
            _this.curTopHeight.push({
              'height': height,
              'left': left
            });
            stop = false;
            break;
          }
        }
      }
    })
  }
},

7. Setting the height of el-load-mask dynamically

getException:function(){
    var oDiv = $('#exceptionDiv')[0];
    var pDiv = $('#el-exception-pane')[0];
    var divHeight = pDiv.offsetHeight > oDiv.offsetHeight ? pDiv.offsetHeight : oDiv.offsetHeight;
    setTimeout(function(){
        var mDiv = pDiv.children[1];
        mDiv.style.height = divHeight +'px';
    },1000);
}

8. Determine the type of string

isString: function (str) {
  return 'String' == utils.getDataType(str);
},
isArray: function (str) {
  return 'Array' == utils.getDataType(str);
},
isObject: function (str) {
  return 'Object' == utils.getDataType(str);
},
isFunction: function (str) {
  return 'Function' == utils.getDataType(str);
},
isNumber: function (str) {
  return 'null' !== str + '' && str !== '' && !isNaN(str);  //'Number' == utils.getDataType(str);
},
isDate: function (str) {
  return 'Date' == utils.getDataType(str);
},
isDateStr: function (str) {
  return utils.dateStrCheck(str);
  //return  'Object' == utils.isObject(str) && str instanceof Date;
},
getDataType: function (str) {
  type = Object.prototype.toString.call(str).slice(8, -1);
  return type;
},

slice(8,-1) means from the 8th place (including the 8th place) to the last place (the meaning of - 1 is the last place, not the last one);
Object.prototype.toString.call(boj) is used to determine the data type.
If boj is a number, the result is [object Number], starting from zero, the eighth place is N, and the last place is r, so we get Number.
If the boj is a string, the result is [object String], the 8th S, the last g, the String.

9. Delete the left and right blanks

trim: function (str) { //Delete the left and right blanks
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

10. Converting Browser Compatible Time Format Objects

tranferCompatibleDate: function (vDate) {
  //var vDate = (typeof vDate == 'string' ? vDate.split('.')[0] : vDate);
  if (utils.isString(vDate) && utils.isDateStr(vDate)) {
    vDate = vDate.replace(new RegExp(/-/gm), '/'); //Converting all'-'to'/' solves the problem that the new Date() of JS in IE and firefox browsers has the values of Invalid Date and NaN-NaN.
    return new Date(vDate);
  } else if (utils.isString(vDate)) { //For this kind of data, the first step is to process "2017-04-15T10:56:31.958Z"
    return new Date(vDate);
  } else if (utils.isDate(vDate)) { //Standard date format Sat Apr 15 2017 13:54:50 GMT+0800 (China Standard Time)
    return new Date(vDate);
  } else if (utils.isNumber(vDate) || utils.isObject(vDate)) {
    try {
      return new Date(vDate);
    } catch (e) {
      console.error('Input object=' + vDate + 'Convert to date object exception!');
      return vDate;
    }
  } else {
    console.error('Incoming date=' + vDate + 'Not the correct date format!');
    return;
  }
}

11. Query the number of days between two dates

dateDayGap: function (dateStrBegin, dateStrEnd) { 
  if (!dateStrBegin || !dateStrEnd) return 0;
  var date1 = utils.tranferCompatibleDate(dateStrBegin);
  var date2 = utils.tranferCompatibleDate(dateStrEnd);
  var s1 = date1.getTime(),
    s2 = date2.getTime();
  var total = (s2 - s1) / 1000;
  var day = parseInt(total / (24 * 60 * 60)); //Calculate Integer Days
  return day;
},

12. Array de-weighting

getArrayNoRepeated: function (arr) {
  if (utils.checkObjTypeIsInvalid(arr, 'Array')) return arr;
  var res = [];
  var json = {};
  for (var i = 0; i < arr.length; i++) {
    if (!json[arr[i]]) {
      res.push(arr[i]);
      json[arr[i]] = 1;
    }
  }
  return res;
}

Posted by rbastien on Thu, 24 Jan 2019 04:06:13 -0800