Typescript动态创建带有循环的数组 [英] Typescript create array with loop dynamically
问题描述
Am创建了一个模拟类,用于为我的Angular2 TypeScript项目生成示例数据.仍然是编程的初学者,并且与有关TypeScript的信息苦苦挣扎.我的问题:
Am creating a mock class, for generate example data for my Angular2 TypeScript project. Am still a beginner with programming, and struggle with the informatie that is available about TypeScript. My question:
我想创建100个项目并将它们保存在一个数组中.这100个项目将动态生成.我使用的静态方法非常简单,但是如何动态地做到这一点呢?我以一些迭代代码作为开始,但是如何最好地替换console.log代码,并将迭代的输出作为静态数据.我需要一些例子
I want to create 100 items and save them in an array. The 100 items will be generated dynamically. The static way i use is very simple, but how do I can do this dynamicly? I made a begin with some iteration code, but how can I best replace the console.log code, and let the output of the iteration be as the static data. I need some examples
mock-names.ts (静态)
export var NAMES: Name[] = [
{"id": 01, "name": "Tony"},
{"id": 02, "name": "Jake"}
]
mock-names-dynamically.ts (动态地)
export var NAMES = [];
for (let i = 1; i < 100; i++) {
console.log(i);
}
name.ts (名称类文件)
export class Name {
id: number;
name: string;
}
推荐答案
您所要做的就是在Javascript中使用数组的push函数.
All you have to do is use the push function of the array in Javascript.
var NAMES = [];
for (let i = 1; i < 100; i++) {
let newName = {
id:i.toString(),
name:"Tony"
};
NAMES.push(newName);
}
这篇关于Typescript动态创建带有循环的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!