How to create a class that prints an array in TypeScript -
i want create array ["name", age] , able print using class:
let person: person[] = [["anne", 21], ["coco", 33]]; class person{ person: person[]; printperson(): person{ (let of person) { document.write( + '<br/>'); } }
this code allow print general nested arrays (i haven't implemented in class easy do):
let persons: (string | number)[][] = [["anne", 21], ["coco", 33]]; const printarray = (array: any[]) => { (const element of array) { if (element instanceof array) { printarray(element); } else { document.write(element.tostring() + '<br/>'); } } } printarray(persons);
output:
anne 21 coco 33
however, since expecting inner arrays have same shape recommend implementing them typescript class. code below defines person
class own write
method, creates array of persons
, , iterates on each 1 , calls write
method:
class person { name: string; age: number; print = () => { document.write(this.name + ' ' + this.age + '<br/>'); }; constructor(name: string, age: number) { this.name = name; this.age = age; } } let persons: person[] = [ new person("anne", 21), new person("coco", 33) ]; (let p of persons) { p.print(); }
output:
anne 21 coco 33
Comments
Post a Comment