Ed L 005
Ed L 005

Reputation: 197

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?

Upvotes: 0

Views: 835

Answers (1)

A. K-R
A. K-R

Reputation: 2002

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

Upvotes: 1

Related Questions