zoukankan      html  css  js  c++  java
  • 这些功能代码,让你成为前端专家

    1. 数组去重

    const numbers =[1, 1, 1, 2, 3, 2, 4]
    let array = Array.from(new Set(numbers)); 
    console.log(array); // Result: [1, 2, 3, 4]

    let array = [...new Set(numbers)]; 
    console.log(array); // Result: [1, 2, 3, 4]

    2. 数组求和

    const arr = [1,2,3,4,5,6,7]
    const sum = arr.reduce((pre,cur)=>{
    return pre +cur
    })
    console.log(sum)
    //Result:28

    3. 获取一个随机布尔值 (true/false)

    const randomBoolean = () => Math.random() >= 0.5;
    console.log(randomBoolean());
    // Result: a 50/50 change on returning true of false

    4. 检查日期是否为工作日

    const isWeekday = (date) => date.getDay() % 6 !== 0;
    console.log(isWeekday(new Date(2021, 0, 11)));
    // Result: true (Monday)
    console.log(isWeekday(new Date(2021, 0, 10)));
    // Result: false (Sunday)

    5. 反转字符串

    const reverse = str => str.split('').reverse().join('');
    reverse('hello world');     
    // Result: 'dlrow olleh'

    6. 检查当前 Tab 页是否在前台

    const isBrowserTabInView = () => document.hidden;
    isBrowserTabInView();
    // Result: returns true or false depending on if tab is in view / focus

    7. 检查数字是否为奇数

    const isEven = num => num % 2 === 0;
    console.log(isEven(2));
    // Result: true
    console.log(isEven(3));
    // Result: false

    8. 从日期中获取时间

    const timeFromDate = date => date.toTimeString().slice(0, 8);
    console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
    // Result: "17:30:00"
    console.log(timeFromDate(new Date()));
    // Result: will log the current time

    9. 保留小数点(非四舍五入)

    const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
    // Examples
    toFixed(25.198726354, 1);       // 25.1
    toFixed(25.198726354, 2);       // 25.19
    toFixed(25.198726354, 3);       // 25.198
    toFixed(25.198726354, 4);       // 25.1987
    toFixed(25.198726354, 5);       // 25.19872
    toFixed(25.198726354, 6);       // 25.198726

    10. 检查元素当前是否为聚焦状态

    const elementIsInFocus = (el) => (el === document.activeElement);
    elementIsInFocus(anyElement)
    // Result: will return true if in focus, false if not in focus

    11. 检查浏览器是否支持触摸事件

    const touchSupported = () => {
      ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
    }
    console.log(touchSupported());
    // Result: will return true if touch events are supported, false if not

    12. 检查当前用户是否为苹果设备

    const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
    console.log(isAppleDevice);
    // Result: will return true if user is on an Apple device

    13. 滚动到页面顶部

    const goToTop = () => window.scrollTo(0, 0);
    goToTop();
    // Result: will scroll the browser to the top of the page

    14. 获取所有参数平均值

    const average = (...args) => args.reduce((a, b) => a + b) / args.length;
    average(1, 2, 3, 4);
    // Result: 2.5

    15. 转换华氏度/摄氏度

    const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
    const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
    // Examples
    celsiusToFahrenheit(15);    // 59
    celsiusToFahrenheit(0);     // 32
    celsiusToFahrenheit(-20);   // -4
    fahrenheitToCelsius(59);    // 15
    fahrenheitToCelsius(32);    // 0

    16. 将任何值转换成布尔值

    使用双感叹号(!!)能将任何内容转换成布尔值
    
    !!true    // true
    !!2       // true
    !![]      // true
    
    !!false   // false
    !!0       // false
    !!" "     // false

    17. 扩展运算符

    连接两个数组数组
    
    const nums1 = [1,2,3]
    const nums2 = [4,5,6]
    
    newArray = [...nums1 ,...nums2 ]   //[1,2,3,4,5,6]
    
    也可以将值推送到数组
    
    let  numbers =  [1,2,3]
    
    numbers = [...numbers , 4, 5] //[1,2,3,4,5]

    18. 检查一个项目是否存在于数组中

    let arrs = [1,2,3];
    
    const hasNumber = arrs.indexOf(1) > -1   //true
    
    或
    
    const hasNumbers = arrs.includes(1)   //true

    19. 避免使用长||检查多个条件链

    const nums = 1
    
    if(num == 1 || num == 2 || num == 3){
       console.log('true')
    }
    
    更简便方法
    
    if([1,2,3].includes(num)){   
       console.log('true')
    }

    20. 数组扁平化

    多维数组=>一维数组 
    let arr = [1, [2, [3, [4, 5]]], 6];
    let str = jsON.stringify(ary);
    
    1.arr.flat(Infinity);//注意:flat和flatMap方法为ES2019(ES10)方法,目前还未在所有浏览器完全兼容。
    
    2.str.replace(/([]))/g, '').split(',');
    
    3.str = str.replace(/([]))/g, '');
    str = '[' + str + ']';
    var ary = jsON.parse(str);

    21. 数字化整数

    const DigitizeInt = n => [...`${n}`].map(i => parseInt(i));
    DigitizeInt(4560) // [4, 5, 6, 0]
    DigitizeInt(131) // [1,3,1]

    22. 修剪空格

    let string = " a b    cd   e   ";
    let Trim = string.replace(/s+/g, '');
    console.log(Trim)

    24. 筛选出有相同key的对象

    let namelist = [{
      name: 'mark',
      age: 15,
      hair: 'long'
    }, {
      name: 'tuwen',
      age: 16,
      hair: 'short'
    }, {
      name: 'xiaoming',
      age: 16,
      hair: 'short'
    }, {
      name: 'lilei',
      age: 15,
      hair: 'short'
    }, {
      name: 'hanmei',
      age: 17,
      hair: 'long'
    }]
    
    ES6
    
    let map = new Map()
    
    namelist.forEach(item => {
        if (map.has(item.age)) {
            map.set(item.age, map.get(item.age).concat(item))
        } else {
            map.set(item.age, [item]) 
        }
    })
    
    console.log(map)
    
    const [arr1, arr2, arr3] = [...map]
    
    结果
    
    arr_1 = [{
      name: 'mark',
      age: 15,
      hair: 'long'
    }, {
      name: 'lilei',
      age: 15,
      hair: 'short'
    }]
    
    arr_2 = [{
      name: 'tuwen',
      age: 16,
      hair: 'short'
    }, {
      name: 'xiaoming',
      age: 16,
      hair: 'short'
    }]
    
    arr_3 = [{
      name: 'hanmei',
      age: 17,
      hair: 'long'
    }]

     

  • 相关阅读:
    实验 7 综合练习一
    实验或作业模版: 实验 6-1 最大公约数 最小公倍数
    实验 6 数组1
    Pro
    作业 4 函数应用
    老大
    双端队列
    zxa and leaf
    Baby Ming and Matrix games
    The more, The Better
  • 原文地址:https://www.cnblogs.com/minihong/p/14867335.html
Copyright © 2011-2022 走看看