Typescript create array with loop dynamically

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

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:

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 (Static)

export var NAMES: Name[] = [     {"id": 01, "name": "Tony"},     {"id": 02, "name": "Jake"} ] 

mock-names-dynamically.ts (Dynamically)

export var NAMES = [];  for (let i = 1; i < 100; i++) {     console.log(i); } 

name.ts (Name Class file)

export class Name {     id: number;     name: string; } 

回答1:

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); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!