简体   繁体   中英

Create an array of user-defined object type

//class Person {} takes in 3 arguments (string ,number, string)

var pArray: Person[ ] = [ ];

var newP;

    for (var i = 0; i < 10; i++) {
        newP = new Person("", Math.floor(Math.random() * 1000), "");
        pArray.push(newP);
    }

Using the above piece of code, i got an array that is filled with 10 numbers, all of which are the same. The result is 10 of the last created number (10th number). This works with primitive types but not object types.

What is going on and how to correct it?

Your code is ok. Put this in the Playground ( http://www.typescriptlang.org/Playground/ ) run it and open the console on the new tapbage:

class Person{
    number1:number;
    constructor(string1 : string, _number1 : number , string2: string){
        this.number1 = _number1;
    }
}


var pArray: Person[ ] = [ ];

var newP;

    for (var i = 0; i < 10; i++) {
        newP = new Person("", Math.floor(Math.random() * 1000), "");
        pArray.push(newP);
    }

    for (var j = 0; j < pArray.length; j++) {
        console.log(pArray[j].number1);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM