js小技巧

var textReg = /(.{10}).*/
var text = "控制文字的長度,其他用***表示"

text.replace(textReg, '$1***')


var mobileReg = /^(\d{3}).*(\d{4})$/  //能夠匹配手機號和座機等
var mobile = "13590244124"

mobile.replace(mobileReg, '$1****$2')

()表明的是 分組,即小括號裏面的小正則 捕獲到的內容。($1--$9 是RegExp 自帶的)web

 

2.浮點數運算數組

function mul() {//乘法
      arguments = Array.from(arguments)//arguments不是真的數組,用不了concat方法
      var m = 0,
        arg = arguments.concat(),
        result = 1;
      arg.forEach((item, index) => {
        arg[index] = item.toString()// item = item.toString()改變不了原數組,若是是對象的就能夠直接修改(js的基本類型 按值傳遞,對象類型按 共享傳遞)
        try {
              if (arg[index].indexOf('.') > -1)
                m += arg[index].split(".")[1].length;
        }catch (e) {
        }
      })
      arg.forEach(item => {
        result *= parseFloat(item.replace(".", ""))
      })
      return result / Math.pow(10, m);
}
function div () {//除
    arguments = Array.from(arguments)
    var m = 0,
        arg = arguments.concat(),
        pow = [],
        result = 1;
    arg.forEach((item, index) => {
        arg[index] = item.toString()
        if(index === 0){
            result *= parseFloat(arg[index].replace(".", ""))
        }
        try {
            if (arg[index].indexOf('.') > -1)
                   pow[index] = arg[index].split(".")[1].length;
        }catch (e) {
        }
    })
     arg.forEach( (item, index) => {
        if(index > 0)
            result /= parseFloat(item.replace(".", ""))
    })
    pow.forEach( (item, index) => {
        if(index === 0 && item){
            m -= item
        }else if(index > 0 && item){
            m += item
        }
    })
    return mul(result, Math.pow(10, m));
}
function add() {//加法
    arguments = Array.from(arguments)
    var m = 0,
        arg = arguments.concat(),
        pow = [],        
        result = 0;
    arg.forEach((item, index) => {
        arg[index] = item.toString()
        try {
            if (arg[index].indexOf('.') > -1)
                pow[index] = arg[index].split(".")[1].length;
        }catch (e) {
        }
    })
    m = Math.pow(10, Math.max(...pow))
    arg.forEach(item => {
        result += mul(item, m)
    })
    return result / m
}
function sub() {//減法
    arguments = Array.from(arguments)
    var m = 0,
        arg = arguments.concat(),
        pow = [],        
        result = 0;
    arg.forEach((item, index) => {
        arg[index] = item.toString()
        try {
            if (arg[index].indexOf('.') > -1)
                pow[index] = arg[index].split(".")[1].length;
        }catch (e) {
        }
    })
    m = Math.pow(10, Math.max(...pow))
    arg.forEach((item, index) => {
    if(index === 0){
        result += mul(item, m)
    }else{
        result -= mul(item, m)
    }
    })
    return result / m
}

 3.encodeURIComponent和decodeURIComponent瀏覽器

對於IE瀏覽器,query參數傳中文字符串最好encodeURIComponent編碼,否則IE9及如下瀏覽器可能出現亂碼問題;緩存

一個字符串,裏面不包含‘%’(有調用decodeURIComponent會報錯),可屢次調用decodeURIComponent進行解碼,內容一致;(%  編碼成 %25)編碼

4. null*1 === 0url

//根據C語言的傳統,null被設計成能夠自動轉爲0
 typeof null === 'object'

//null是一個表示"無"的對象,轉爲數值時爲0;undefined是一個表示"無"的原始值,轉爲數值時爲NaN。

5 + undefined 爲 NaN

//null表示"沒有對象",即該處不該該有值。典型用法是:
//做爲對象原型鏈的終點。

Object.getPrototypeOf(Object.prototype) === null

5. 左移運算符,右移運算符運用spa

2.3>>1  //1
-2.3>>1 //-1

//對於左運算,相似於先捨棄小數部分再乘於2的n次方向下取整
2.7<<2   能夠理解成2*2^2

//對於右運算,相似於先捨棄小數部分再除於2的n次方向下取整
-12.7>>2   能夠理解成-12/(2^2) 爲-3
-15.9>>2   能夠理解成-15/(2^2) 爲-4

 6. 關於谷歌彈出默認選擇密碼框的問題prototype

//當input的type爲password的時候會自動彈出默認密碼選擇框

//方法一:初始化的時候設置type爲text,而後監聽onChange事件
//當value不爲空時置type爲password
// 弊端,瀏覽器自動填充密碼的時候會明文

//方法二:設置爲readOnly,當得到焦點的時候,延遲設置e.target.readOnly=false
// 當失去焦點的時候,從新設置e.target.readOnly=true

7. 選用瀏覽器的密碼填充後,會出現默認的背景色設計

&:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px #272789 inset;//背景色
    -webkit-text-fill-color: #FFF;//填充文字顏色
    caret-color: #FFF;//鼠標顏色
}

 8. 避免瀏覽器緩存get請求code

request.interceptors.request.use(function (config) {
  // let token = window.localStorage.getItem('token') || ''
  // if(token){
  //   config.headers['Authorization'] = 'bearer ' + token
  // }

  if(config.method.toLowerCase() === 'get'){
    if (!config['params']) { //若是這個請求自己不帶參數
      Object.assign(config, {   //給options這個對象添加一個params的參數,屬性爲_,值爲時間戳
        params: {
          _: new Date().getTime()
        }
      })
    } else {
      Object.assign(config.params, { //若是get請求自己帶有參數,給options.params 再添加一個key值_,值爲時間戳
        _: new Date().getTime()
      })
    }
  }

  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

 9. 判斷是否爲IE

isIE = () => {
    // return window.navigator.userAgent.indexOf('MSIE') > -1; //ie 11 失效
    if (!!window.ActiveXObject || "ActiveXObject" in window){
      return true;
    }else {
      return false;
    }
  }

10 window.open(url) 和window.open(url, '__blank') 的區別

區別在於從主頁面window.open(url) 永遠都是新開個標籤頁,window.open(url, '__blank')會檢測若是已經從主頁面新開標籤頁,會複用

緣由:

window.open(strUrl, strWindowName, [strWindowFeatures]);

//strWindowName 新窗口的名稱。該字符串能夠用來做爲超連接 <a> 或表單 <form> 元素的目標屬性值。字符串中不能含有空白字符。注意:strWindowName 並非新窗口的標題。

這裏之因此複用新標籤頁,是由於'__blank',只是單獨的一個名稱,而非'_blank'

若是已經存在以 strWindowName 爲名稱的窗口,則再也不打開一個新窗口,而是把 strUrl 加載到這個窗口中。在這種狀況下,方法的返回值是這個已經打開的窗口,並忽略參數 strWindowFeatures 。若是要在每次調用 window.open()時都打開一個新窗口,則要把參數 strWindowName 設置爲 _blank。若是要在本標籤頁打開,則設置爲_self

 11. 深度合併對象以及深度合併對象的某些屬性

function deepExtend(obj1, obj2) {
  if (Object.prototype.toString.call(obj1) === '[object Object]' && Object.prototype.toString.call(obj2) === '[object Object]') {
    for (let prop2 in obj2) {//obj1無值,都有取obj2
      if (!obj1[prop2]) {
        obj1[prop2] = obj2[prop2];
      } else {//遞歸賦值
        obj1[prop2] = deepExtend(obj1[prop2], obj2[prop2]);
      }
    }
  } else if (Object.prototype.toString.call(obj1) === '[object Array]' && Object.prototype.toString.call(obj2) === '[object Array]') {
    // 兩個都是數組,簡單進行替換
    // obj1 = obj2;
    for (let prop2 in obj2) {//obj1無值,都有取obj2
      if (!obj1[prop2]) {
        obj1[prop2] = obj2[prop2];
      } else {//遞歸賦值
        obj1[prop2] = deepExtend(obj1[prop2], obj2[prop2]);
      }
    }
  } else {//其餘狀況,取obj2的值
    obj1 = obj2;
  }
  return obj1;

}

function deepExtendSomeAttrs(obj1, obj2, attrs, prop) {
  if (Object.prototype.toString.call(obj1) === '[object Object]' && Object.prototype.toString.call(obj2) === '[object Object]') {
    for (let prop2 in obj2) {//obj1無值,都有取obj2
      if (!obj1[prop2]) {
        if(attrs && attrs.includes(prop2)){
          obj1[prop2] = obj2[prop2];
        }
        if(!attrs){
          obj1[prop2] = obj2[prop2];
        }
      } else {//遞歸賦值
        obj1[prop2] = deepExtendSomeAttrs(obj1[prop2], obj2[prop2], attrs, prop2);
      }
    }
  } else if (Object.prototype.toString.call(obj1) === '[object Array]' && Object.prototype.toString.call(obj2) === '[object Array]') {
      if(attrs && attrs.includes(prop)){
        if(obj1.length < obj2.length){
          obj1 = obj2;
        }
      }
      if(!attrs){
        for (let prop2 in obj2) {//obj1無值,都有取obj2
          if (!obj1[prop2]) {
              if(attrs && attrs.includes(prop2)){
              obj1[prop2] = obj2[prop2];
              }
              if(!attrs){
              obj1[prop2] = obj2[prop2];
              }
          } else {//遞歸賦值
              obj1[prop2] = deepExtendSomeAttrs(obj1[prop2], obj2[prop2], attrs, prop2);
          }
        }
      }

  } else {//其餘狀況,取obj2的值
    if(attrs && attrs.includes(prop)){
      obj1 = obj2;
    }
    if(!attrs){
      obj1 = obj2;
    }
  }
  return obj1;

}
相關文章
相關標籤/搜索