better2021 / Blog

个人博客
https://feiyuweb.me/Blog
1 stars 0 forks source link

js代码片段及实用方法 #5

Open better2021 opened 5 years ago

better2021 commented 5 years ago

获取链接 https://www.baidu.com?name=jawil&age=23 name的value值

function getParamName(attr) {

  let match = RegExp(`[?&]${attr}=([^&]*)`) //分组运算符是为了把结果存到exec函数返回的结果里
    .exec(window.location.search)
  //["?name=jawil", "jawil", index: 0, input: "?name=jawil&age=23"]
  return match && decodeURIComponent(match[1].replace(/\+/g, ' ')) // url中+号表示空格,要替换掉
}

console.log(getParamName('name'))  // "jawil"
better2021 commented 5 years ago

数字货币格式化问题,1234567890 --> 1,234,567,890

let test1 = '1234567890'
let format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')

console.log(format) // 1,234,567,890
better2021 commented 5 years ago

去掉字符串左右两边的空格," jaw il " --> “jaw il”

function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "")
}

let str = "  jaw il "
console.log(trim(str)) // "jaw il"
better2021 commented 5 years ago

获取指定数字对应的日期或时间

function formatDate(v) {
  return {
    '0': '昨日',
    '1': '今日',
    '7': '最近7天',
    '30': '最近30天'
  }[v]
}

formatDate(7)  // "最近7天"
better2021 commented 5 years ago

js对字符串图片等类型的加解密

安装 npm install crypto-js


var CryptoJS = require("crypto-js");//replace thie with script tag in browser env

//encrypt var rawStr = "hello world!"; var wordArray = CryptoJS.enc.Utf8.parse(rawStr); var base64 = CryptoJS.enc.Base64.stringify(wordArray); console.log('encrypted:', base64);

//decrypt var parsedWordArray = CryptoJS.enc.Base64.parse(base64); var parsedStr = parsedWordArray.toString(CryptoJS.enc.Utf8); console.log("parsed:",parsedStr);

better2021 commented 5 years ago

element-ui 的el-table 的增加key,避免多个一样列表时导致不重新渲染

添加row-key="id"即可

<el-table
:key="curRadio"
v-loading="loading.table"
row-key="id"
:data="list"
border
fit
highlight-current-row
stripe
</el-table>

如果有重复id则需要添加函数方法 :row-key="getRowKeys"


<el-table
:key="curRadio"
v-loading="loading.table"
:row-key="getRowKeys"
:data="list"
border
fit
highlight-current-row
stripe
</el-table>

// 获取row的key值 getRowKeys(row) { const id = row.id + row.realDomain return id }

better2021 commented 5 years ago

new URLSearchParams(当前url地址?后的参数)获取 ?后的参数

// 例如当前url地址为 'http://localhost:3000/?a=5&b=100'
new URLSearchParams(location.search).get('b')  // 100
new URLSearchParams(location.search).get('a')  // 5

// 可以包装为一个函数
function getParam(name){
   return new URLSearchParams(location.search).get(name)
   // 或者 return  new URL(location.href).searchParams.get(name)
}
better2021 commented 5 years ago

获取cookie

function getCookie(name) 
{ 
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");

    if(arr=document.cookie.match(reg))

        return unescape(arr[2]); 
    else 
        return null; 
}
getCookie('Hm_lpvt_f477da77241dafc76e6667d65a762e75')
better2021 commented 5 years ago

判断某个html标签中是否有某个属性

例如:判断a标签中是否含有download属性(有的浏览器中a标签没有download属性)

'download' in document.createElement('a')
better2021 commented 5 years ago

获取文件的扩展名

const getFileExt = filename => {
  return filename.slice(((filename.lastIndexOf('.') - 1) >>> 0) + 2)
}
better2021 commented 5 years ago

构建 FormData 表单

const formBuilder = obj => {
  const formData = new FormData()
  Object.keys(obj).forEach(k => {
    formData.append(k, obj[k])
  })
  return formData
}
better2021 commented 5 years ago

数组平变化后,找到对应id的name值

const list = res.data
      let newArr = []
      list.forEach(i => {
        newArr.push(i.apps)
      })
      newArr = newArr.flat()
      console.log(newArr, "-*-")

      const idStr = "15,16,45,27"
      const arrId = idStr.split(",")

      let arr = newArr.filter(i => arrId.find(j => Number(j) === i.id))
      let result = arr.map(item => item.name)

      console.log(result, "--")
better2021 commented 5 years ago

数组转化为数组对象格式

const obj = {
        data: [
          "user_id,name,number",
          "1,cshy01,15812358752",
          "4,cshy02,13532534125",
          "7,cshy03,15309021031",
          "10,cshy04,13457597240",
          "31,testgl,",
          "34,a888888,",
          "37,999999,",
          "40,testgl1,",
          "43,0,",
          "46,777777,",
          "49,viva1234,18680317116",
          "55,666666,",
          "88,liulei5,",
          "160,ab2222,",
          "252,zz12345,",
          "329,13576267006,13576267006",
          "392,yuue123,13787841123",
          "399,liulian,17687694910",
          "402,15980507106,15980507106",
          "406,15583612727,15583612727",
          "419,buo6789,",
          "538,aa2233,18898761432",
          "539,testfff,",
          "557,bing777,15855681276",
          "568,lijin1,13004685597",
          "583,q88888,",
          "599,qwerty,18576671578",
          "600,ryl123456,18256511764",
          "604,980106,",
          "605,xlj417441265,15228234269",
          "607,weiyicheng,13665632333",
          "616,Silence,13674952401",
          "664,test009,",
          "675,15716335093,",
          "678,Suoha1,18102181480",
          "681,13405120608,13405120608",
          "324,13791671729,13791671729",
          "708,17698873165,17698873165",
          "710,18278393488,18278393488",
          "725,19943004567,19943004567",
          "767,13730764040,13730764040",
          "776,15738768579,15738768579",
          "779,15007785743,15007785743",
          "781,15176486101,15176486101",
          "817,15839204152,15839204152",
          "819,18998468095,18998468095",
          "827,15920437062,15920437062",
          "869,15812616901,15812616901",
          "870,15030779809,15030779809",
          "880,17630708521,17630708521",
          "919,15336261824,15336261824",
          "926,15968670056,15968670056",
          "930,18703880821,18703880821",
          "933,13812609350,13812609350",
          "1831,13771491989,13771491989",
          "1834,13754531281,13754531281",
          "1839,15220276807,15220276807",
          "1841,18532234139,18532234139"
        ],
        attributes: null,
        state: 0,
        message: "\u64cd\u4f5c\u6210\u529f"
      }

      const array = obj.data
      // console.log(array, "--")
      let oneArr = array[0].split(",")
      console.log(oneArr, "-**-")

      let newList = []
      array.forEach((item, i) => {
        //  console.log(item.split(","), "item")
        const itemArr = item.split(",")
        if (i !== 0) {
          const obj = {}
          oneArr.forEach((k, j) => {
            obj[k] = itemArr[j]
          })

          newList.push(obj)
        }
      })
      console.log(JSON.stringify(newList), "--")
better2021 commented 5 years ago

多层数据递归获取全部checked为true的id集合

  let dataSource = {
      data: {
        auth: [
          {
            id: 8,
            pid: 0,
            children: [
              {
                id: 23,
                pid: 8,
                leaf: true,
                checked: false
              }
            ]
          },
          {
            id: 7,
            pid: 0,
            children: [
              {
                id: 20,
                pid: 7,
                leaf: true,
                checked: false
              },
              {
                id: 21,
                pid: 7,
                leaf: true,
                checked: false
              },
              {
                id: 24,
                pid: 7,
                leaf: true,
                checked: false
              }
            ]
          },
          {
            id: 6,
            pid: 0,
            children: [
              {
                id: 19,
                pid: 6,
                leaf: true,
                checked: true
              }
            ]
          },
          {
            id: 1,
            pid: 0,
            children: [
              {
                id: 12,
                pid: 1,
                leaf: true,
                checked: false
              },
              {
                id: 11,
                pid: 1,
                children: [
                  {
                    id: 106,
                    pid: 11,
                    leaf: true,
                    checked: true
                  },
                  {
                    id: 107,
                    pid: 11,
                    leaf: true,
                    checked: true
                  },
                  {
                    id: 108,
                    pid: 11,
                    leaf: true,
                    checked: true
                  },
                  {
                    id: 109,
                    pid: 11,
                    leaf: true,
                    checked: true
                  }
                ]
              },
              {
                id: 10,
                pid: 1,
                children: [
                  {
                    id: 102,
                    pid: 10,
                    leaf: true,
                    checked: false
                  },
                  {
                    id: 100,
                    pid: 10,
                    leaf: true,
                    checked: false
                  },
                  {
                    id: 101,
                    pid: 10,
                    leaf: true,
                    checked: false
                  },
                  {
                    id: 103,
                    pid: 10,
                    leaf: true,
                    checked: false
                  },
                  {
                    id: 104,
                    pid: 10,
                    leaf: true,
                    checked: false
                  },
                  {
                    id: 105,
                    pid: 10,
                    leaf: true,
                    checked: false
                  }
                ]
              }
            ]
          },
          {
            id: 2,
            pid: 0,
            children: [
              {
                id: 22,
                pid: 2,
                leaf: true,
                checked: false
              },
              {
                id: 15,
                pid: 2,
                leaf: true,
                checked: true
              },
              {
                id: 14,
                pid: 2,
                leaf: true,
                checked: true
              },
              {
                id: 13,
                pid: 2,
                leaf: true,
                checked: false
              }
            ]
          },
          {
            id: 3,
            pid: 0,
            children: [
              {
                id: 16,
                pid: 3,
                leaf: true,
                checked: false
              }
            ]
          },
          {
            id: 4,
            pid: 0,
            children: [
              {
                id: 17,
                pid: 4,
                leaf: true,
                checked: false
              }
            ]
          },
          {
            id: 5,
            pid: 0,
            title: '\u5ba2\u670d',
            children: [
              {
                id: 18,
                pid: 5,
                leaf: true,
                checked: false
              }
            ]
          }
        ],
        user: {
          true_name: '',
          bank_card: true,
          address_book: '',
          user_search_switch: false
        },
        user_search_switch: false
      },
      attributes: null,
      state: 0,
      message: '\u64cd\u4f5c\u6210\u529f'
    };

    const data = dataSource.data.auth;
    console.log(data);

    /*
      多层数据递归获取全部checked为true的id集合      
      */

    function loop(list, result = []) {
      list.forEach(o => {
        if (o.checked) {
          result.push(o.id);
        }
        if (o.children) {
          loop(o.children, result);
        }
      });
      return result;
    }

    let arrId = loop(data);
    console.log(arrId);
better2021 commented 4 years ago

cors与jsonp的对比

CORS 与 JSONP 的使用目的相同,但是比 JSONP 更强大。JSONP 只支持GET请求,CORS 支持所有类型的 HTTP 请求。JSONP 的优势在于支持老式浏览器,以及可以向不支持 CORS 的网站请求数据

better2021 commented 4 years ago

使用Boolean过滤数组中的所有假值

我们知道JS中有一些假值:false,null,0,"",undefined,NaN,怎样把数组中的假值快速过滤呢,可以使用Boolean构造函数来进行一次转换

const compact = arr => arr.filter(Boolean)
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34])   // [1, 2, 3, "a", "s", 34]
better2021 commented 4 years ago

双位运算符 ~~

可以使用双位操作符来替代正数的 Math.floor( ),替代负数的Math.ceil( )。双否定位操作符的优势在于它执行相同的操作运行速度更快。

~~4.5                // 4
Math.floor(4.5)      // 4
Math.ceil(4.5)       // 5

~~-4.5                // -4
Math.floor(-4.5)     // -5
Math.ceil(-4.5)      // -4
better2021 commented 4 years ago

取整 | 0

对一个数字| 0可以取整,负数也同样适用,num | 0

1.3 | 0         // 1
-1.9 | 0        // -1
better2021 commented 4 years ago

禁止鼠标右键,禁止拖拽及选中复制

<body ondragstart="window.event.returnValue=false;return false;" oncontextmenu="window.event.returnValue=false;return false;" onselectstart="event.returnValue=false;return false;"></body>
better2021 commented 4 years ago

让整个页面的body可编辑和不可编辑

document.body.contentEditable = "true"  // 页面可以编辑
document.body.contentEditable = "false"  // 页面不可编辑