[英]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.