码迷,mamicode.com
首页 > 编程语言 > 详细

前端常用算法

时间:2020-06-26 14:29:03      阅读:62      评论:0      收藏:0      [点我收藏+]

标签: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<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

 

前端常用算法

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!