前端常用算法

2021-05-04 16:31

阅读:412

标签:http   com   fun   xxx   lse   exchange   出现   dfs   替换   

  // 数组倒排
  let numArray = [3, 6, 2, 4, 1, 5];
  function reverse(array) {
      let result= [];
      for(var i = array.length-1; i>= 0; i--) {
           result.push(array[i]);
      }
      return result;
   }
   numArray = reverse(numArray);
   console.log(numArray); // [5,1,4,2,6,3] 
    // 数组去重
    let arr1 = [‘a‘, ‘b‘, ‘c‘, ‘a‘, ‘b‘];
    console.log([...new Set(arr1)])  // [‘a‘, ‘b‘, ‘c‘]
    // 获取url中参数
    let url = "http://item.taobao.com/item.html?a=1&b=2&c=&d=xxx";
    let str = url.substr(url.indexOf(‘?‘) + 1);  // a=1&b=2&c=&d=xxx
    let arr = str.split("&");    // ["a=1", "b=2", "c=", "d=xxx"]

    let obj = {};
    for(let i=0; i) {
        let item = arr[i];
        let temArr = item.split("="); // [‘a‘, ‘1‘]
        obj[temArr[0]] = temArr[1] 
    }
    console.log(obj);  // {a: "1", b: "2", c: "", d: "xxx"}
    // 正则匹配
    // 问题:将字符串‘
{$id}
{$name}
‘中
    // 的{$id}替换成10,{$name}替换成Tony 
    let str = ‘
{$id}
{$name}
‘;
    let str1 =  str.replace(/{\$id}/g, ‘10‘).replace(/{\$name}/g, ‘Tony‘);
    console.log(str1);
  // 统计字符串出现最多的次数
  let str = ‘asdfssaaasasasasaa‘;
  let obj = {};
  for(let i = 0; i) {
    if(!obj[ str[i] ]) {
      obj[ str[i] ] = 1;
    } else {
      obj[ str[i] ]++;
    }
  }
  console.log(obj);  // {a: 9, s: 7, d: 1, f: 1}
  let iMax = 0;
  let letter= ‘‘;
  for(let i in obj) {
    if(obj[i] > iMax) {
      iMax = obj[i];
      letter = i;
    }
  }
  console.log(‘出现次数最多的是:‘+ letter + ‘出现‘ + iMax+‘次‘);
    // 千分位标注
    function exchange(num) {
        num += ‘‘; // 转成字符串
        if (num.length return num; }
        num = num.replace(/\d{1,3}(?=(\d{3})+$)/g, (v) => {
            return v + ‘,‘;
        });
        return num;
    }
    console.log(exchange(1234567));  // 1,234,567

 

前端常用算法

标签:http   com   fun   xxx   lse   exchange   出现   dfs   替换   

原文地址:https://www.cnblogs.com/guwufeiyang/p/13194562.html


评论


亲,登录后才可以留言!