如何在 typescript 中实现以下 JavaScript 代码。
var childs = [];
childs[34] = [12,23,54,65];
childs[122] = [43,56,23,31];
childs[212343] = [345,643,24,745];
console.log(childs);
最佳答案
您的代码已经是有效的 typescript 代码,因为 typescript 是 javascript 的超集。
但是,typescript 允许您拥有类型,因此在这种情况下您可以这样做:
var childs: number[][] = [];
childs[34] = [12,23,54,65];
childs[122] = [43,56,23,31];
childs[212343] = [345,643,24,745];
console.log(childs);
请注意,我添加的唯一内容是 childs
的类型 (number[][]
),也可以这样写:
var childs: Array<number[]> = [];
// or
var childs: Array<Array<number>> = [];
如果您尝试向数组添加任何其他内容,您将收到编译器错误:
childs.push(4); // error: Argument of type '4' is not assignable to parameter of type 'number[]'
childs.push([2, "4"]); // error: Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'
关于javascript - 如何创建数组并为 typescript 中的任何索引赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42885220/