类似Python中的enumerate
test.ts
/*
* 枚举 迭代器
* 支持:Array, Tuple, Map, String
* */
function * enumerate(obj: unknown, start: number=0){// Array or Tupleif (Array.isArray(obj)){let num = startfor (let j of obj){yield [num, j]num += 1}// Map}else if (typeof obj == "object" && obj != null){let num = startfor (let[key, value] of Object.entries(obj)){yield [num, {key, value}]num += 1}// String}else if (typeof obj == "string" && obj != null){let num = startfor (let j of obj.split("")){yield [num, `${j}`]num += 1}}else {throw new TypeError("unsupport type of ".concat(typeof obj))}
}// 测试样例
let arg = [1, "2", false] as Array < any >
// let arg = {"1": 1, "2": false, "3": 3}
// let arg = "4365476ghjfghadfgad"
let enu = enumerate(arg, 0)let flag = false
while (!flag) {let res = enu.next()if (res.done) {flag = !flag} else {/*使用类型断言来告诉 TypeScript 编译器 res.value 的确切类型报错信息如下:test.ts:497:13 - error TS2488: Type 'void | any[]' must have a '[Symbol.iterator]()' method that returns an iterator.497 let [index, value] = res.value~~~~~~~~~~~~~~Found 1 error.*/let [index, value] = res.value as any[]console.log(index, value, typeof value)}
}
编译命令:
tsc --target es2017 test.ts