九个JavaScript的简单技巧

九个JavaScript技巧

1.生成指定范围的数字

在某些情况下我们会创建一个处在两个数之间的数组.假设我们要判断某人的生日是否在摸个范围的年份内,那么下面是实现它的一个简单方法

    let start = 1900, end = 2000
    [...new Array(end + 1).keys()].slice(start)

    // or
    Array.from( {length: end - start + 1}, (_, i) => start + i)

2.使用值数组最为函数的参数

在某些情况下,我们需要将值收集到数组中,然后将其最为函数的参数传递.使用ES6,可以使用扩展运算符...并从[arg1,arg2] > (arg1, arg2)中提取数组

    const parts = {
        first: [0, 2],
        second: [1, 3]
    }

   ["Hello", "World", "JS", "Tricks"].slice(...parts.second)
   // ["World", "JS"]

3.将值作用Math方法的参数

当我们需要在数组中使用Math.maxMath.min来找到最大或者最小值时,我们可以像下面这样进行操作:

    const elementsHeight = [...document.body.children].map(
        el => el.getBoundingClientRect().y
    )
    Math.max(...elementsHeight)

    const numbers = [100, 100, -1000, 2000, -3000, 40000]
    Math.min(...numbers)

4.合并/展平数组中的数组

Array有一个很好的方法,Array.flat,它是需要一个depth参数, 表示数组嵌套的深度,默认为1.但是我们不知道深度怎么办,则需要将其全部展平,只需要将Infinity作为参数即可

    const arrays = [[10], 50, [100, [2000, 3000, [40000]]]]
    arrays.flat(Infinity)

    // [ 10, 50, 100, 2000, 3000, 40000 ]

5.防止代码崩溃

在代码中出现不可预测的行为是不好的,但是如果你有这种行为,需要处理它.
例如,常见错误TypeError,试获取undefined/null等属性,就会报这个错误

    const found = [{ name: "Alex" }].find(i => i.name === 'Jim')

    console.log(found.name)
    // TypeError: Cannot read property 'name' of undefined

可以这样避免它:

    const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {}

    console.log(found.name)
    // undefined

6. 传递参数的好方法

对于这个方法,一个很好的用例就是styled-components,在ES6中,我们可以将模板字符串中作为函数的参数传递而无需使用方括号.如果要实现格式化/转换文本的功能,这是一个很好的技巧

    const makeList = (raw) =>
    raw
        .join()
        .trim()
        .split("\n")
        .map((s, i) => `${i + 1}. ${s}`)
        .join("\n");

    makeList`
    Hello, World
    Hello, World
    `
    // 1. Hello,World
    // 2. World,World

7.交换变量

使用解构赋值语法,我们可以轻松地减缓变量

    let a = "hello"
    let b = "world"

    // 错误的方式
    a = b
    b = a
    // { a: 'world', b: 'world' }

    // 正确的做法
    [a, b] = [b, a]
    // { a: 'world', b: 'hello' }

8.按字符顺序排序

需要在跨国际的项目中,对于按字典排序,一些比较特殊的语言可能会出现问题

    // 错误的做法
    ["a", "z", "ä"].sort((a, b) => a - b);
    // ['a', 'z', 'ä']

    // 正确的做法
    ["a", "z", "ä"].sort((a, b) => a.localeCompare(b));
    // [ 'a', 'ä', 'z' ]

localeCompare() :用本地特定的顺序来比较两个字符串。

9.隐藏隐私

屏蔽字符串,当你需要屏蔽任何变量时(不是密码)

    const word = "hackme";
    word.substr(-3).padStart(word.length, "*");
    // ***kme
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值