Arrays in type script

后端 未结 3 456
陌清茗
陌清茗 2021-02-05 00:52

I am finding difficulty declaring array in typescript and accessing it.

below is the code working for me

class Book {
    public BookId: number;
    publ         


        
相关标签:
3条回答
  • 2021-02-05 01:17

    You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

    class Book {
        public BookId: number;
        public Title: string;
        public Author: string;
        public Price: number;
        public Description: string;
    }
    
    var bks: Book[] = [];
    
     bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.
    
    0 讨论(0)
  • 2021-02-05 01:32

    A cleaner way to do this:

    class Book {
        public Title: string;
        public Price: number;
        public Description: string;
    
        constructor(public BookId: number, public Author: string){}
    }
    

    Then

    var bks: Book[] = [
        new Book(1, "vamsee")
    ];
    
    0 讨论(0)
  • 2021-02-05 01:33

    This is a very c# type of code:

    var bks: Book[] = new Book[2];
    

    In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:

    var bks: Book[] = [];
    bks.push(new Book());
    bks[0].Author = "vamsee";
    bks[0].BookId = 1;
    return bks.length;
    

    Now to explain what new Book[2]; would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:

    Book[2] = function (){alert("hey");}
    var foo = new Book[2]
    

    and you should see hey. Try it

    0 讨论(0)
提交回复
热议问题