美文网首页
TypeScript和JavaScript的一些小技巧记录

TypeScript和JavaScript的一些小技巧记录

作者: 前端混合开发 | 来源:发表于2019-01-04 09:32 被阅读0次

    原文地址:https://hk.saowen.com/a/b2f3cbdef137a4ce6a65e6ad1b45ea0b3e490d1fe6677c2a95d2dd6b305e8e98

    Math类中ceil、floor、round取整介绍

    Math类中提供了三个与取整有关的方法:ceil、floor、round,这些方法的作用与它们的英文名称的含义相对应,
    例如,ceil的英文意义是天花板,该方法就表示向上取整,
    所以,Math.ceil(11.3)的结果为12,Math.ceil(-11.3)的结果是-11;floor的英文意义是地板,该方法就表示向下取整,
    所以,
    Math.floor(11.6)的结果为11,
    Math.floor(-11.6)的结果是-12;
    最难掌握的是round方法,它表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果为12,Math.round(-11.5)的结果为-11。

    ceil 向上取整
    floor向下取整
    round四舍五入
    简写:

    var num = 4.5;
    ~~num;
    num << 0;
    num >> 0;
    num >>> 0;

    字符串转数字

    parseInt("4.5"); // 4
    parseFloat("4.5"); // 4.5
    parseInt({a:1}); // NaN
    简写:

    var num = "4.5";
    +num; // 4.5
    
    num = {a:1};
    +num; // NaN
    

    转Boolean值

    Boolean(5.99); // true
    Boolean(0); // false
    Boolean(1); // true
    Boolean(null); // false
    Boolean(undefined); // false
    Boolean(""); // false
    Boolean("1"); // true
    Boolean({}); // true
    

    简写:

    !!5.99; // true
    !!0; // false
    !!1; // true
    !!null; // false
    !!undefined; // false
    !!""; // false
    !!"1"; // true
    !!{}; // true
    

    void 0

    如果编写的代码会直接发布,尽可能用 void 0 代替 null 和 undefined,因为在某些浏览器中,undefined可以被赋值导致判断全部错误。

    比如在TS中,编译后,使用到的undefined都会替换为 void 0

    TS

    多使用接口方式
    比如传递参数时,这么写:

    func(a: Point);
    

    只能接受Point类型的变量,如果用下面的写法:

    func(a: {x:number, y:number});
    

    就可以接受带有x和y的所有变量,可以更好的复用该函数。

    快速得到属性

    一般的写法:

    let x = point.x;
    let y = point.y;
    

    简写:

    let {x, y} = point;
    

    快速写入属性

    一般的写法:

    let a = 0;
    let b = "heelo";
    let obj = {a: a, b: b};
    

    简写:

    let a = 0;
    let b = "heelo";
    let obj = {a, b};
    

    参数类类型控制

    比如我们需要传递一个参数,该参数是MyClass类的类型,而不是实例时,一般只能用any,实际上是可以指定类型的,写法如下:

    public func(classType: { new(): MyClass }): void;
    

    传入类型,得到该类型的实例

    一般用于工厂或对象池等:

    export function getInstance<T>(Class: {new () : T}): T {
      return new Class();
    }
    

    单例的简写方式

    static get instance(): Obj {
      return this._instance || (this._instance = new Obj());
    }
    

    类属性控制

    interface IObj {
      // 可选属性
      name?: string;
      // 只读属性
      readonly age: number;
    }
    

    控制动态属性:

    interface Map<T> {
      [key: string]: T;
    }
    

    用接口来规范一个对象

    比如我们有一个接口,可以用下面的方法来规范一个对象,而不用编写一个实现该接口的类:

     1 export interface IPoint {
     2   x: number;
     3   y: number;
     4 }
     5 
     6 export function foo(point: IPoint) {
     7   // ...
     8 }
     9 
    10 foo(<IPoint> {x: 100, y: 100});
    

    如果打错属性名称或缺少必须的属性会报错,属性类型不匹配也会报错,可以大大降低写错的问题。另外添加额外属性是允许的。

    相关文章

      网友评论

          本文标题:TypeScript和JavaScript的一些小技巧记录

          本文链接:https://www.haomeiwen.com/subject/lvthrqtx.html