创建2维数组 [英] creating 2 dimension arrays

查看:95
本文介绍了创建2维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS新手,需要一些基本的帮助:

我有一个电子表格,里面有一个方形的数据矩阵。



我可以如下读取这些数据:

  var freqArr = new Array(new Array()); 
var freqSheet = SpreadsheetApp.getActiveSpreadsheet()。getSheetByName(freq);
var freqRows = freqSheet.getDataRange();
var freqNumRows = freqRows.getNumRows();
freqArr = freqSheet.getRange(2,2,freqNumRows,freqNumRows).getValues();

我现在想在内存中创建一个类似于我从表单中读取的数组

  var tempArr = new Array(new Array()); (var j = 0; j <= 3; j ++){
tempArr [i] [j(i = 0; i ++){
) ] = freqArr [i] [j];


$ / code>

只要j从0增加到1,I尝试在tempArr [i] [j]中存储任何内容TypeError:无法将未定义的属性0.0设置为xxx



解决方案

比我更聪明的人可能可以帮助您编写此代码更好,但它看起来对我来说就是你想创建tempArr作为主数组,它内部会有 2 数组。



这些数组的内部都是值,所以:

  // result:tempArr = [[1,2], (var i = 0; i< = 3; i ++){
tempArr [i] = [] []]
tempArr = [] //或new Array
;
for(var j = 0; j< = 3; j ++){
tempArr [i] .push(freqArr [i] [j]);
}
}

在tempArr中创建第一个主数组,因为,每当你循环时,tempArr [i]被创建为一个数组,并且在第二个内部,你想要将freqArr的值推送到内部数组。



UPDATE 在tempArr [i]中有一个空格会导致它无法正常工作。对不起!


I am new to JS and need some basic help:

I have a spreadsheet which has a square matrix of data.

I can read these data as follows:

  var freqArr     = new Array(new Array());
  var freqSheet   = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("freq");
  var freqRows    = freqSheet.getDataRange();
  var freqNumRows = freqRows.getNumRows();
  freqArr = freqSheet.getRange(2, 2, freqNumRows, freqNumRows).getValues();

I now want to create a an array in memory similar to the one I have read from the sheet

 var tempArr = new Array(new Array());
  for (var i = 0; i <= 3; i++) {
    for (var j = 0; j <= 3; j++) {        
      tempArr [i][j] = freqArr[i][j] ;
    }
  }

As soon as j incs from 0 to 1 and I try to store anything in tempArr [i][j] I get an error "TypeError: Cannot set property "0.0" of undefined to "xxx"

I have tried every combination of creating tempArr that I can think of plus a few more.

解决方案

Someone much smarter than myself could probably help you write this better, but the way it looks to me is that you want to create tempArr as the main array, which would have 2 arrays inside of it.

Inside of each of those arrays are values, so:

// result: tempArr = [[1,2],[4,5]]
tempArr = [] // or new Array
for (var i = 0; i <= 3; i++) {
  tempArr[i] = [];
  for (var j = 0; j <= 3; j++) {        
    tempArr[i].push(freqArr[i][j]);
  }
}

You create your first main array in tempArr, within your for, each time you loop through, tempArr[i] is created as an array, and inside of the second for, you want to push the value of freqArr to the inner array.

UPDATE Had a space in tempArr[i] that would've caused it to not work for sure. Sorry!

这篇关于创建2维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆