简体   繁体   English

如何在二维数组中设置值?

[英]How to set values in a bidimensional array?

First of all, sorry about my skills;首先,对不起我的技能; my coding background is zero and I am just trying to modify an script to fit my needs.我的编码背景为零,我只是想修改一个脚本以满足我的需要。

I need to setValues in a two-rows datasheet data range.setValues在两行数据表数据范围内设置值。

The current script sets the values in the first row.当前脚本设置第一行中的值。 How should I modify the script so I can get the data from my 4 values in 2 rows?我应该如何修改脚本,以便我可以从 2 行中的 4 个值中获取数据?

Current behaviour:当前行为:

当前的

My go-to behaviour:我的首选行为:

去

Function to run: Print Function 运行:打印

function Print() {

   SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet").getRange(1, 1, 1, 2).setValues(Data());    

}

function Data() {

    var array = [];

                      var score = "retrieved score";
                      var time = (2+2);
                      var device = "device";
                      var speed = 3+3;

    array.push([score,time]);

    Utilities.sleep(1000);

    return array;
}

Problem问题

Trying to set 2 x 2 matrix of values to 1 x 2 range尝试将 2 x 2 值矩阵设置为 1 x 2 范围

Solution解决方案

Your values have to match dimensions of the range.您的值必须与范围的尺寸相匹配。 The sheet is a matrix consisting of cells:工作表是由单元格组成的矩阵:

|       |       col 1       | col 2 |
| ----- | ----------------- | ----- |
| row 1 | "retrieved score" |   4   |
| row 2 | "device"          |   6   |

2-dimensional arrays are basically the same, where outer level represents rows and inner - columns:二维 arrays 基本相同,其中外层表示行,内层表示行:

[
  [ "retrieved score", 4 ],
  [ "device", 6 ]
]

Thus, with a simple modification, the cells should be filled correctly:因此,通过简单的修改,单元格应该被正确填充:

function Print() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();

  const rng = ss.getSheetByName("sheet").getRange(1, 1, 2, 2);

  const values = Data();

  rng.setValues(values);    

}

function Data() {

  var array = [];

  var score = "retrieved score";
  var time = 2+2;
  var device = "device";
  var speed = 3+3;

  array.push([score, time], [device, speed]);

  Utilities.sleep(1000);

  return array;
}

Notes笔记

  1. It does not make sense to me that you need to use the sleep() utility method here.你需要在这里使用sleep()实用程序方法对我来说没有意义。 Operations on an in-memory array are synchronous and atomic (which is not true for setValues , as it is an I/O operation).内存数组上的操作是同步的和原子的(对于setValues来说不是这样,因为它是一个 I/O 操作)。

References参考

  1. push() method reference on MDN MDN 上的push()方法参考
  2. setValues() method reference setValues()方法参考

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

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