zoukankan      html  css  js  c++  java
  • ES6高级技巧(三)

    html转译

    let c='<a href="#">Me & you</a>'.replace(/[&<>'"]/g,item=>{
      let a={
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        "'": '&#39;',
        '"': '&quot;'
      };
      return a[item]||item
      }
    )
    console.log(c)
    

    数字前面加密

    const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask);
    
    mask(1234567890); // '******7890'
    mask(1234567890, 3); // '*******890'
    mask(1234567890, -4, '$'); // '$$$$567890'
    

    字符串倒序

    const reverseString = str => [...str].reverse().join('');
    
    reverseString('foobar'); // 'raboof'
    

    字符串升序

    localeCompare 可以用来判断升序还是降序

    const sortCharactersInString = str =>
    [...str].sort((a, b) => a.localeCompare(b)).join('');
    

    字符串 数组交换位置

    字符串

    const stringPermutations = str => {
      if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
      return str
        .split('')
        .reduce(
          (acc, letter, i) =>
            acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),
          []
        );
    };
    
    stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba']
    

    数组

    const permutations = arr => {
      if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
      return arr.reduce(
        (acc, item, i) =>
          acc.concat(
            permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
          ),
        []
      );
    };
    

    promise一种写法

    let a=Promise.resolve([1,2,3,4]).then(res=>res.map(v=>v*5))
    
    a.then(res=>{
      console.log(res)
      })
    

    事件委托的另一种方式填充数据

    <div id="a"></div>
    <script>
      let a = document.querySelector('#a')
      let arr = ['1', '2']
      a.innerHTML+=arr.map(val=>`<li>${val}</li>`).join('')
    </script>
    

    正则

    不能是开头:(?<!^)
    三个数字:(d{3})
    后面要正好是3的整数倍个数字:(?=(d{3})*$)
    合起来就是 /(?<!^)(d{3})(?=(d{3})*$)/g,我们需要一个g表示全局匹配,测试一下:
    const newRegexp = /(?<!^)(d{3})(?=(d{3})*$)/g
    const numStr = '1234567890'
    console.log(numStr.match(newRegexp))
    // ["234", "567", "890"]
    

    in

    如果是数组,返回索引

    如果是对象,返回属性

    算法和数据结构

    资料

    在sort()方法中,V8引擎对sort方法执行小于10个使用插入排序,大于十个使用快速排序

    对于多个条件,使用Array.includes

    const checkCarModel = (model) => {
        if(model === 'renault' || model === 'peugeot') { 
        console.log('model valid');
        }
    }
    
    checkCarModel('renault'); // 输出 'model valid'
    
    修改版
    const checkCarModel = (model) => {
        if(['peugeot', 'renault'].includes(model)) { 
        console.log('model valid');
        }
    }
    

    匹配所有条件,使用Array.every 或者Array.find

    const checkEveryModel = (model) => {
      return cars.every(car => car.model === model);
    }
    
    const checkEveryModel = (model) => {
      return cars.find(car => car.model !== model) === undefined;
    }
    

    匹配部分条件

    const cars = [
      { model: 'renault', year: 1956 },
      { model: 'peugeot', year: 1968 },
      { model: 'ford', year: 1977 }
    ];
    
    const checkForAnyModel = (model) => {
      return cars.some(car => car.model === model);
    }
    

    如何避免if多层分支

    先考虑不符合条件的情况

    如果A不符合的,B不符合的,A&&B不符合的

    使用索引或者映射,而不是switch

    反例

    const getCarsByState = (state) => {
      switch (state) {
        case 'usa':
          return ['Ford', 'Dodge'];
        case 'france':
          return ['Renault', 'Peugeot'];
        case 'italy':
          return ['Fiat'];
        default:
          return [];
      }
    }
    

    修改版

    const cars = new Map()
      .set('usa', ['Ford', 'Dodge'])
      .set('france', ['Renault', 'Peugeot'])
      .set('italy', ['Fiat']);
    
    const getCarsByState = (state) => {
      return cars.get(state) || [];
    }
    
    console.log(getCarsByState()); // 输出 []
    console.log(getCarsByState('usa')); //输出 ['Ford', 'Dodge']
    console.log(getCarsByState('italy')); // 输出 ['Fiat']
    

    或者(这个很牛逼)

    const carState = {
      usa: ['Ford', 'Dodge'],
      france: ['Renault', 'Peugeot'],
      italy: ['Fiat']
    };
    
    const getCarsByState = (state) => {
      return carState[state] || [];
    }
    
    console.log(getCarsByState()); // 输出 []
    console.log(getCarsByState('usa')); // 输出 ['Ford', 'Dodge']
    console.log(getCarsByState('france')); // 输出 ['Renault', 'Peugeot']
    

    ###########################.............................................................................................................................................................................................

  • 相关阅读:
    SQLI DUMB SERIES-12
    SQLI DUMB SERIES-11
    SQLI DUMB SERIES-9&&10
    SQLI DUMB SERIES-8
    SQLI DUMB SERIES-7
    XXS level10
    XXS level9
    XXS level8
    XXS level7
    XXS level6
  • 原文地址:https://www.cnblogs.com/fangdongdemao/p/11125833.html
Copyright © 2011-2022 走看看