• 前端常用算法


      // 数组倒排
      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<arr.length; 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"}
        // 正则匹配
        // 问题:将字符串'<tr><td>{$id}</td><td>{$name}</td></tr>'中
        // 的{$id}替换成10,{$name}替换成Tony 
        let str = '<tr><td>{$id}</td><td>{$name}</td></tr>';
        let str1 =  str.replace(/{$id}/g, '10').replace(/{$name}/g, 'Tony');
        console.log(str1);
      // 统计字符串出现最多的次数
      let str = 'asdfssaaasasasasaa';
      let obj = {};
      for(let i = 0; i<str.length; 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 <= 3) { return num; }
            num = num.replace(/d{1,3}(?=(d{3})+$)/g, (v) => {
                return v + ',';
            });
            return num;
        }
        console.log(exchange(1234567));  // 1,234,567
      // 得到一个两数之间的随机整数,包括两个数在内
      function getRandomInclusive(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max -min +1)) + min;
      }
      var number = getRandomInclusive(10, 1000);
      console.log(number); // 437
  • 相关阅读:
    模板
    模板
    模板
    模板
    2017-2018 ACM-ICPC Asia Tsukuba Regional Contest
    牛客
    软件工程
    Codeforces Round 696(Div.2)
    Atcoder ARC111 contest
    Codeforces Educational Round 100(Div.2)
  • 原文地址:https://www.cnblogs.com/guwufeiyang/p/13194562.html
Copyright © 2020-2023  润新知