生成具有随机值 TypeScript 的二维数组
generate 2d array with random values TypeScript
我尝试在打字稿上生成二维数值数组
初始化:
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
]
]
我尝试在打字稿上生成二维数值数组 初始化:
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
]
]