问题描述
我尝试在打字稿上生成二维数值数组 初始化:
weight: number[][] = [];
和世代价值:
private generateWeights(): void {
this.weight = [];
for (let i = 0; i < 7; i++) {
this.weight[i] = [];
for (let j = 0; j < 5; j++) {
this.weight[i][j] = Math.random() * 2;
}
}
console.log('this.weight: ',this.weight);
}
但在控制台上我得到一些静态值,如图片:
当我尝试打印二维数组的行时,我得到了奇怪的 console.log:
解决方法
我将 a playground 与一种您可以使用的方法结合在一起,至少在单独运行时效果很好。抱歉,不知道您的代码的其余部分是什么样子的,因此很难看出您遇到问题的原因。
function generateWeights(rows: number,cols: number): number[][] {
return Array.from({ length: rows }).map(() =>
Array.from({ length: cols }).map(() => Math.random() * 2)
);
}
//example invocation
console.log(JSON.stringify(generateWeights(7,5),null," "));
示例调用产生...
[
[
1.9665769596410398,0.32225623317750873,1.979382321105576,1.3400841950364906,0.0333557898363388
],[
0.523308974899896,0.519975189295653,0.14464403965018624,0.7799904829432234,0.7748489552011621
],[
1.2637757372417209,0.9375011277636429,0.46157500412620367,0.7470383909903693,0.45140251266154596
],[
0.9576573640144601,0.7096653222305775,1.7104635189269257,0.16415705266079472,0.38377189535968403
],[
0.04732945754404572,0.7050064626827024,0.8450634927445284,0.12460094121473508,0.6501398542245567
],[
0.5087564269629801,0.8193243695084456,1.4786471319572896,0.35962390487698004,1.5651415242853055
],[
0.31416888386760533,1.088122706073758,0.9604222417055066,0.6956030508790003,1.6623759187576028
]
]