JavaScript技巧

1、生成指定范围内的数字

    // 生成1到100的数字
    let start = 1, end = 100
    let arr = [...new Array(end + 1).keys()].slice(start)
    console.log(arr)

    let arr1 = Array.from({ length: end - start + 1 }, (_, i) => start + i)
    console.log(arr1)

2、使用值数组作为函数的参数

    // 可以通过...扩展运算符提取对象中的数组
    const obj = {
      first: [0, 2],
      second: [1, 3]
    }
    let arr = ['one', 'two', 'three', 'four']
    let arr1 = arr.slice(...obj.second)
    let arr2 = arr.slice(1, 3)
    let arr3 = arr.slice([1, 3])

    console.log(arr) // ["one", "two", "three", "four"]
    console.log(arr1) // ["two", "three"]
    console.log(arr2) // ["two", "three"]
    console.log(arr3) // ["one", "two", "three", "four"]

3、数组扁平化:利用flat()方法,传入Infinity

    const arr = [[1, 2, 3], 4, [5, 6, [7, 8]]]
    const newArr = function (arr) {
      return arr.reduce(
        (pre, cur) => pre.concat(Array.isArray(cur) ? newArr(cur) : cur),
        []
      );
    };
    console.log(newArr(arr)) // [1, 2, 3, 4, 5, 6, 7, 8]
    const arr = [[1, 2, 3], 4, [5, 6, [7, 8]]]
    const arr1 = arr.flat(Infinity)
    console.log(arr1) // [1, 2, 3, 4, 5, 6, 7, 8]

4、短路语句防止代码奔溃:|| {} 加了这个后,没有name属性会打印undefined,如果没有会报错Uncaught TypeError: Cannot read property 'name' of undefined

    const arr = [{ name: "wxm" }, { name: "sunyizhen" }]
    const obj = arr.find(item => item.name === 'sunyizhen') || {}
    console.log(obj.name)

5、sort()方法,利用localeCompare()处理特殊字符的排序

    var points = [1, 3, 2, 0]
    console.log(points.sort()) // 默认顺序 [0, 1, 2, 3]
    console.log(points.sort((a, b) => { return a - b })) // 顺序 [0, 1, 2, 3]
    console.log(points.sort((a, b) => a - b)) // 同上
    console.log(points.sort((a, b) => { return b - a })) // 倒序 [3, 2, 1, 0]

    let arr1 = ['a', 'c', 'b', "ä"].sort()
    let arr2 = ['a', 'c', 'b', "ä"].sort((a, b) => a.localeCompare(b))

    console.log(arr1) // ["a", "b", "c", "ä"]
    console.log(arr2) // ["a", "ä", "b", "c"]

6、屏蔽字符串,隐藏密码-padStart()方法:头部补全,第一个参数是补全后字符串多长,第二个参数是用什么字符串补全

    const password = "hackme";
    let str = password.substr(-3).padStart(password.length, "*");
    console.log(password) // hackme
    console.log(str) // ***kme
原文地址:https://www.cnblogs.com/wuqilang/p/13751842.html