简体   繁体   中英

adding together two 2d arrays in javascript

I am having trouble this problem regarding 2d arrays. We must create a javascript function addArrays(al, a2) which takes in two 2d arrays of numbers, a1 and a2 and returns their "sum" in the sense of the matrix sum. If If a is array with the sum, then, for all rows i and all columns j, a[i][j] = a1[i][j] + a2[i][j].

I am completely stumped I am pretty sure my logic to find the sum is right but I don't know if anything is actually stored in the sum array or what this error means. Any help would be greatly appreciated.

This is the code I have so far:

var sum = new Array(a1.length);
for (var k = 0; k<sum.length; k++) {
    sum[k] = new Array(sum.length);
}

for (var l = 0; l<sum.length; l++) {
    for (var m = 0; m<sum.length[l]; m++) {
        sum[l][m].push(a1[l][m] + a2[l][m]);
    }
}

return sum;

We are given a test file:

 function start() {  
  var ar1 = [[1,2], [3,4]],
  ar11 = [[1,2], [3,4], [5,6]],
  ar12 = [[1,2,3], [3,4]],

  ar2 = [[6,7], [8,9]],
  ar21 = [[6,7], [8,9], [19,11]],
  ar22 = [[6,7], [8,9,10]],

  ar;

  try {
     alert( addArrays(ar1, ar2).toSource() );
  }
  catch (e) {
      alert( e );
  }}

When I run the program I keep getting the error: TypeError: addArrays(...).toSource is not a function

error: TypeError: addArrays(...).toSource is not a function

Means it cannot find the function toSource on what is beign returned by addArrays . Object.toSource is not part of any standard and should not be used.

From MDN

Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Looking at the output of toSource it looks similar to JSON. You can change the test to utilize JSON.stringify to achieve a similar output.

 function start() {  
  var ar1 = [[1,2], [3,4]],
  ar11 = [[1,2], [3,4], [5,6]],
  ar12 = [[1,2,3], [3,4]],

  ar2 = [[6,7], [8,9]],
  ar21 = [[6,7], [8,9], [19,11]],
  ar22 = [[6,7], [8,9,10]],

  ar;

  try {
     alert( JSON.stringify(addArrays(ar1, ar2)) );
  }
  catch (e) {
      alert( e );
  }}

For same size arrays you can invent some Array method like Array.prototype.matriceSum() as follows;

 Array.prototype.matriceSum = function(a) { return this.reduce((p,c,i) => (p[i] = c.reduce((f,s,j) => (f[j]+= s,f),p[i]),p),a.slice()); }; var a1 = [[1,2,3],[2,2,2],[4,5,6]], a2 = [[6,6,6],[9,8,7],[6,5,4]]; a3 = a1.matriceSum(a2); console.log(JSON.stringify(a3)); 

This won't mutate the array it's called upon and return a new 2D array with the matrix addition of the two 2D arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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