0
//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?

2
  • What exactly are you trying to accomplish? your question is unlcear, as is your explanation Commented Nov 18, 2013 at 7:58
  • 1
    How are you checking your results? I suspect the problem is in your "checking" code, not your "creating" code. Commented Nov 18, 2013 at 9:02

1 Answer 1

1

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.