typescript常用代码片段

1. 对象属性遍历

遍历方式1:使用Object.keys

const p = {
    name: li,
    age: 18
}

Object.keys(p).forEach((key)=>{
    console.log((p as any)[key])
});

遍历方式2:使用keyof

interface IPerson {
    name: string;
    age: number;
}

function test(opt: IPerson) {
    let key: (keyof IPerson);
    for (key in opt) {
        console.log(opt[key]);
    }
}

遍历方式3:使用Object.entries

const obj = {
    name: li,
    age: 18,
};

Object.entries(obj).forEach(([k, v]) => {
    console.log(k, v);
});

遍历方式4:使用for in

const obj = {
    name: li,
    age: 18,
};

for (let k in obj) {
    console.log((obj as any)[k]) 
}

2. 数组遍历

方法一:for…of

let array = [1, 2, 3];
for (let entity of array) {
    console.log(entity);
}

方法二: for循环

let array = [1, 2, 3];
for(let i=0; i<array.length; i++) {
    console.log(array[i])
}

方法三:forEach

let list = [1, 2, 3];
list.forEach((val, idx, array) => {
    // val: 当前值
    // idx:当前index
    // array: Array
});

方法四,every和some 因为forEach在iteration中是无法返回的,所以可以使用every和some来取代forEach。

let list = [1, 2, 3];
list.every((val, idx, array) => {
    // val: 当前值
    // idx:当前index
    // array: Array
    console.log(`val=${val}`)
    return true; // Continues
    // Return false will quit the iteration
});

3. Map嵌套定义

export class UnitSystem {
    allUnitSystem: { [key: string]: { [key: string]: string } } = {
        SI1: {
            length: 1,
        },
        SI2: {
            length: 2,
        }
    }
}
经验分享 程序员 微信小程序 职场和发展