简体   繁体   English

JavaScript 中锯齿状多维数组中的逐元素算术运算

[英]Element-Wise Arithmetic Operations in Jagged Multidimensional Arrays in JavaScript

I want to perform some element-wise arithmetric or mathematical operations on 2D jagged-arrays without flattening the output array;我想在不展平输出数组的情况下对二维锯齿状数组执行一些元素式算术或数学运算; in this example, array C.在本例中,数组 C。

 const A = [[1, 2, 30, 4],[5, 16, 7],[8, 9, 12, 14, 90]]; const B = [[45, 60, 15, 35],[45, 55, 75],[12, 34, 80, 65, 90]]; const C = []; for (let j = 0; j < A.length; j++) { for (let k = 0; k < A[j].length; k++) { C.push(0.5*A[j][k] + B[j][k]); } } console.log(C)

I have tried using a for loop but the output, C, is flattened.我曾尝试使用 for 循环,但输出 C 被压平了。 Also, I have used mathjs library function, but it seems the element-wise arithmetic operations in this library only works for non-jagged multidimensional arrays.此外,我使用了 mathjs 库函数,但似乎该库中的元素算术运算仅适用于非锯齿状多维数组。

You could map the inner arrays and get a new arra of arrays with the wanted values.您可以映射内部数组并获得具有所需值的新数组数组。

 const a = [[1, 2, 30, 4],[5, 16, 7],[8, 9, 12, 14, 90]], b = [[45, 60, 15, 35],[45, 55, 75],[12, 34, 80, 65, 90]], c = a.map((inner, i) => inner.map((v, j) => 0.5 * v + b[i][j])); console.log(c);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM