JavaScript – 小技巧 Tips

发布时间 2023-09-03 16:38:14作者: 兴杰

1e6 等价于 1 + 后面 6 个零

console.log(1e6 === 1_000_000);

 

模拟 C# 的 Record Deconstruct

class Size implements Iterable<number> {
    constructor(
        public width : number, 
        public height: number
    ) {}

    *[Symbol.iterator]() {
        yield this.width;
        yield this.height
    }
}

const size = new Size(100, 200);

const [width, height] =  size; // 100, 200

利用 Iterable 可以让对象支持 Array 式 的 Deconstruct.

property 数量可控的情况下,这种方式会比 Object 式 的 Deconstruct 容易重命名。