简体   繁体   English

创建用户定义对象类型的数组

[英]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. 使用上面的代码,我得到了一个充满10个数字的数组,所有这些都是相同的。 The result is 10 of the last created number (10th number). 结果是最后创建的号码(第10个)中的10个。 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: 将其放在Playground( http://www.typescriptlang.org/Playground/ )中运行并在新的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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在QBasic中的用户定义的TYPE中使用数组 - Use an array in a user-defined TYPE in QBasic 用户定义类型和将数组传递给函数 - User-defined Type & passing Array to Function 数组 VBA 中的用户定义对象 - User-Defined Object In Array VBA 如何创建一个自动实例化的元素数组,例如用户定义类型的int数组? - How to create an element auto-instantiated array such as the int arrays of an user-defined type? 有没有办法在java中制作用户定义的类类型的数组? - Is there a way to make an array of a user-defined class type in java? 如何将新元素添加到用户定义类型的数组? - How to add new elements to an array of a user-defined type? 堆栈或堆栈数组。 用户定义的类型难题 - To heap or stack array. A user-defined type conundrum 存储在数组中时包含指针中断的用户定义 object - User-defined object containing pointer breaks when stored in array VBA函数似乎返回一个数组,但我收到“类型不匹配:预期为数组或用户定义类型” - VBA function seems to return an array but I get “Type mismatch: array or user-defined type expected” VBA子调用给出“编译错误:类型不匹配:数组或用户定义的类型预期” - VBA sub call gives “compile error: Type mismatch: array or user-defined type expected”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM