zoukankan      html  css  js  c++  java
  • JavaScript高级小技巧

    使用&&替代if

    const doSometings = () => {}
    
    const isTrue = true
    let temp = ''
    if(isTrue){
        doSometings()
        temp = 'isTrue'
    }
    
    // 替代方案
    isTrue && this.doSometings()
    isTrue && (temp = 'isTrue')

    [] or {} => null (永远不要相信后端返回的数据)

    const { data } = await getApiData()
    
    // 如果data类型是一个数组
    console.log(data[0]) // 如果data返回了个null,会报错
    
    // 如果data类型是一个对象
    console.log(data.a) // 如果data返回了个null,会报错
    
    // 可以写成下面这样
    console.log((data || [])[0])
    console.log((data || {}).a)
    // 此时就算data返回了null,也只会提示undefined,并不会报错阻塞代码

    生成长度为N的数组

    // 生成长度为100的数组
    const arrN = [...Array(100).keys()]
    // [0,1,2,3,...,99]

    生成A-Z的数组

    const AZCodeArr = [...Array(91).keys()].filter(i => i > 64).map(i => String.fromCharCode(i))
    //['A','B','C','D'...]

    取最后一位数字

    const num = 12345
    const num2 = '54321'
    console.log(num%10) // 5
    console.log(num2%10) // 1 当然隐式转换也是可以的

    取整

    const num = 123.456
    console.log(num | 0) // 123

    写一个中间件管理你的工具类

     

    // index.js
    
    [
      'utilA',
      'utilB'
    ].forEach(m => {
      Object.assign(exports, require(`./lib/${m}`))
    })
    
    exports.lodash = require('lodash')
    
    
    // 外部引用
    const { utilA, utilB, lodash : _ } = require('utils')

    万能reduce

    累加

    const arr = [
        {num:1},
        {num:2},
        {num:3}
    ]
    console.log(arr.reduce((p,n) => p + n.num, 0)) // 6

    去重

    // 去除id重复的对象
    const arr = [
      {
        id: "1",
        msg: "",
      },
      {
        id: "2",
        msg: "",
      },
      {
        id: "1",
        msg: "",
      },
    ];
    console.log(
      arr.reduce((p, n) => {
        if (!p.find((i) => i.id === n.id)) {
          p.push(n);
        }
        return p;
      }, [])
    ); // [{id:'1',msg:''},{id:'2',msg:''}]

    获取查询参数

    如果我们想要获取URL中的参数,可以使用window对象的属性:

    window.location.search

    如果一个URL为www.baidu.com?project=js&type=1 那么通过上面操作就会获取到?project=js&type=1。如果在想获取到其中某一个参数,可以这样:

    let type = new URLSearchParams(location.search).get('type');

    数字取整

    ~~3.1415926  // 3

    除了这种方式之外,我们还可以使用按位与来实现数字的取整操作,只需要在数字后面加上|0即可:

    23.9 | 0   // 23
    -23.9 | 0   // -23

    检查对象是否为空

    Object.keys({}).length  // 0
    Object.keys({key: 1}).length  // 1

    值转为布尔值

    通常我们如果想显式的值转化为布尔值,会使用Boolean()方法进行转化。其实我们可以使用!!运算符来将一个值转化我布尔值。
    这种操作相对于Boolean()方法性能会快很多,因为它是计算机的原生操作:
    !!undefined // false
    !!"996"     // true
    !!null      // false
    !!NaN       // false
    
    

    格式化 JSON 代码

    JSON.stringify(value, replacer, space)

    它有三个参数:

    • value:将要序列化成 一个 JSON 字符串的值。
    • replacer 可选:如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;如果该参数为 null 或者未提供,则对象所有的属性都会被序列化。
    • space 可选:指定缩进用的空白字符串,用于美化输出(pretty-print);如果参数是个数字,它代表有多少的空格;上限为10。该值若小于1,则意味着没有空格;如果该参数为字符串(当字符串长度超过10个字母,取其前10个字母),该字符串将被作为空格;如果该参数没有提供(或者为 null),将没有空格。

    console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));

    
    
    
    
    
    
    
    
    
    
    
    
  • 相关阅读:
    交通运输线(LCA)
    POJ 2186 Popular cows(Kosaraju+强联通分量模板)
    Codeforces 351D Jeff and Removing Periods(莫队+区间等差数列更新)
    Codeforces 375D
    Codeforces 86D
    SPOJ D-query(莫队算法模板)
    Educational Codeforces Round 25 D
    Codeforces Round #423 Div. 2 C-String Reconstruction(思维)
    HDU3974 Assign the task(多叉树转换为线段+线段树区间染色)
    bzoj 2463: [中山市选2009]谁能赢呢?
  • 原文地址:https://www.cnblogs.com/magicg/p/15787446.html
Copyright © 2011-2022 走看看