范围方法getValues()返回和setValues()接受什么?

发布于 2025-02-10 04:04:09 字数 947 浏览 2 评论 0 原文

我想从我的工作表中获得范围。如

const ss = Spreadsheet.getActive(),
  sh = ss.getSheetByName("Sheet1"),
  rg = sh.getRange("A1:C1"),//has 1,2,3
  values = rg.getValues();
console.log(values);

日志显示

[[1,2,3]]

,您可以看到我收到了所有三个元素。但是,当我记录数组的长度( array.length )时,它只是1(而不是3)。当我使用 .indexof .concludes 测试元素的存在时,它说-1或 false

const values = /*same as logged above*/[[1,2,3]];
console.log(values.indexOf(2));//got -1 expected 1
console.log(values.includes(1));//got false expected true

为什么?

我对 setValues()也有同样的问题。

rg.setValues([1,2,3]);//throws error

错误是

“参数(number [])不匹配电子表格app.range.setValues的方法签名。”

我的具体问题是: getValues()返回到底是什么?这是一种特殊的数组吗?

I want to get a range from my sheet. As recommended in Best practices, I am trying to get a array and manipulate it, but I'm confused:

const ss = Spreadsheet.getActive(),
  sh = ss.getSheetByName("Sheet1"),
  rg = sh.getRange("A1:C1"),//has 1,2,3
  values = rg.getValues();
console.log(values);

The logs show

[[1,2,3]]

As you can see I got all three elements. But, when I log the length of the array(array.length), it is just 1(instead of 3). When I test existence of a element using .indexOf or .includes, It says -1 or false.

const values = /*same as logged above*/[[1,2,3]];
console.log(values.indexOf(2));//got -1 expected 1
console.log(values.includes(1));//got false expected true

Why?

I have the same issue with setValues().

rg.setValues([1,2,3]);//throws error

The error is

"The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues."

My specific Question is: What exactly does getValues() return? Is it a special kind of array?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

违心° 2025-02-17 04:04:10

文档摘录:

官方文档 )返回

二维值

始终返回a 两个尺寸值阵列

一维数组是

[1,2,3]

二维数组的数组中

[[1,2,3]]
//or
[[1], [2], [3]]

有/是数组中的数组。

由行索引,然后是列。

首先,它由行索引:IE,外部阵列的行作为内数阵列。然后每个内部阵列都有列元素。考虑以下简单电子表格:

A B C
1> 1 2 3
2> 2 3 4
3> 3 4 5

a1:a3 包含3行,每行包含1列元素。这表示为 [[1],[2],[3]] 。同样,以下范围代表以下数组。尝试根据a1表示法猜测数组结构:

a1
列表
编号
列的行
array数组
结构
阵列数组
.length
Array [0]
.length
A1 :a3 3 1 [[1],[2],[3],[3] 3 1
a1:c1 1 3 [[1,2,3]] 1 3
A1 :b2 2 2 [[1,2],[2,3]] 2 2
b1:c3 3 2 [[2,3],[3,4],[4,[4,[4,] 5]] 3 2
a2:c3 2 3 [[2,3,4],[3,4,5]] 2 3 3

请注意二维如何提供方向。
请参阅下面的实时可视化:

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
const test = {
  'A1:A3': [[1], [2], [3]],
  'A1:C1': [[1, 2, 3]],
  'A1:B2': [
    [1, 2],
    [2, 3],
  ],
  'B1:C3': [
    [2, 3],
    [3, 4],
    [4, 5],
  ],
  'A2:C3': [
    [2, 3, 4],
    [3, 4, 5],
  ],
};

Object.entries(test).forEach(([key, value]) => {
  console.log(`The range is ${key}`);
  console.table(value);
  console.info(`The above table's JavaScript array notation is ${JSON.stringify(value)}`)
  console.log(`=================================`);
});
<!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

根据单元格的值。

在上面的示例中,我们具有转换为JavaScript号码类型的电子表格编号类型元素。您可以使用 type(type() )。对应的JavaScript类型参考是在这里

空单元用数组中的一个空字符串表示。

检查使用

console.log(values[0][0]==="")//logs true if A1 is empty    

请记住,范围索引从1、1开始,而JavaScript数组则从[0] [0]。

索引。

给定二维数组结构,要访问一个值,需要两个格式 array [row] [column] 的索引。在上表中,如果检索 a2:c3 ,则访问 c3 ,请使用 values [1] [2] [1] 是范围A2:C3的第二行。请注意,范围本身从第二行开始。因此,在中,第二行给定范围是行 3 [2] 是第三列 c

注意:

  • 警告:

从一个范围内检索的值始终二维,无论范围高或宽度如何(即使仅1)。 getRange(“ a1”)。getValues()将表示 [[1]

  • setValues()将接受与对应于该阵列相对应的相同数组结构范围设置。如果尝试使用一维数组,则错误

参数(number []/string [])不匹配电子表格Appapp.range.setValues的方法签名。

被扔了。

  • 如果数组不完全对应于所设置的范围,即,如果内部数组的长度中的每个阵列都不对应于范围内的列数或外部阵列的长度与该范围内的行数不符被设置为类似以下错误的错误:

数据中的列数与范围内的列数不匹配。数据有5个,但范围为6。

参考:

Documentation excerpts:

From The official documentation, getValues() returns

a two-dimensional array of values,

It ALWAYS returns a two dimensional array of values.

One dimensional array is

[1,2,3]

Two dimensional array is

[[1,2,3]]
//or
[[1], [2], [3]]

There is/are array(s) inside a array.

indexed by row, then by column.

It is indexed by row first: i.e., The outer array has rows as inner array. Then each inner array has column elements. Consider the following simple spreadsheet:

A B C
1> 1 2 3
2> 2 3 4
3> 3 4 5

A1:A3 contains 3 rows and each row contains 1 column element. This is represented as [[1],[2],[3]]. Similarly, The following ranges represent the following arrays. Try to guess the array structure based on the A1 notation:

A1
Notation
Number
of Rows
Number
of columns
Array
Structure
array
.length
array[0]
.length
A1:A3 3 1 [[1],[2],[3]] 3 1
A1:C1 1 3 [[1,2,3]] 1 3
A1:B2 2 2 [[1,2],[2,3]] 2 2
B1:C3 3 2 [[2,3],[3,4],[4,5]] 3 2
A2:C3 2 3 [[2,3,4],[3,4,5]] 2 3

Note how the two dimension provides direction.
See live visualization below:

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
const test = {
  'A1:A3': [[1], [2], [3]],
  'A1:C1': [[1, 2, 3]],
  'A1:B2': [
    [1, 2],
    [2, 3],
  ],
  'B1:C3': [
    [2, 3],
    [3, 4],
    [4, 5],
  ],
  'A2:C3': [
    [2, 3, 4],
    [3, 4, 5],
  ],
};

Object.entries(test).forEach(([key, value]) => {
  console.log(`The range is ${key}`);
  console.table(value);
  console.info(`The above table's JavaScript array notation is ${JSON.stringify(value)}`)
  console.log(`=================================`);
});
<!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

The values may be of type Number, Boolean, Date, or String, depending on the value of the cell.

In the above example, We have Spreadsheet Number type elements converted to JavaScript number type. You can check spreadsheet type using =TYPE(). Corresponding JavaScript type reference is here

Empty cells are represented by an empty string in the array.

Check using

console.log(values[0][0]==="")//logs true if A1 is empty    

Remember that while a range index starts at 1, 1, the JavaScript array is indexed from [0][0].

Given the two dimensional array structure, to access a value, two indexes of format array[row][column] is needed. In the above table, if A2:C3 is retrieved, To access C3, Use values[1][2]. [1] is second row in range A2:C3. Note that the range itself starts on second row. So, second row in the given range is row3 [2]is third column C.

Notes:

  • Warning:

Retrieved values from a range is always two dimensional regardless of the range height or width(even if it is just 1). getRange("A1").getValues() will represent [[1]]

  • setValues() will accept the same array structure corresponding to the range to set. If a 1D array is attempted, the error

The parameters (number[]/string[]) don't match the method signature for SpreadsheetApp.Range.setValues.

is thrown.

  • If the array does NOT exactly correspond to the range being set,i.e.,if each of the the inner array's length does not correspond to the number of columns in the range or the outer array's length does not correspond to the number of rows in the range being set, The error similar to the following is thrown:

The number of columns in the data does not match the number of columns in the range. The data has 5 but the range has 6.

  • Related answers to the above error:

  • indexOf/includes uses strict type checking. They won't work when you compare primitives against array objects. You can use Array.flat to flatten the 2D array to a 1D one. Alternatively, Use a plain old for-loop to check something.

    const values = [[1,2,3]].flat();//flattened
    console.log(values.indexOf(2));//expected 1
    console.log(values.includes(1));//expected true

References:

蘸点软妹酱 2025-02-17 04:04:10

如果您要填充将写入电子表格范围的数组,则可以将其初始化为2个昏暗数组,因此:

var dataTable = [[]] ;    // Data that will be written to sheet

If you are going to be populating an array that will be written to a spreadsheet range you can initialize it as a 2 dim array like so:

var dataTable = [[]] ;    // Data that will be written to sheet
聽兲甴掵 2025-02-17 04:04:10

我遇到了类似的问题,并且偶然发现了 flat()方法,用于使[[1,2,3]]数组变平[1,2,3]。果然,不仅 flat()> getValues()返回的对象的2个DIM数组,而且还将对象重新构成正确的数字和字符串! huzzah!

表格数据的屏幕截图

这是我的测试脚本:

function listOflists (){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

// Load data from the spreadsheet.
// display data array
var DeckID = spreadsheet.getRange("B2:B50").getValues();
Logger.log(DeckID); // [[2D array]]

// First attempt to filter out desired elements
var values = DeckID
var filteredValues = values.filter(isString);

  function isString(value) {
  Logger.log(value + " is an " + typeof value); // Everything is an object !
  return typeof value === "string"; // which renders this comparison useless
  }

Logger.log(filteredValues); // null result

// Revised attempt to filter out desired elements
// by first using the flat method on the 2D array
var values = DeckID.flat(); 
Logger.log(values); // [1D array]


var filteredValues = values.filter(isString);

  function isString(value) {
  Logger.log(value + " is an " + typeof value);
  return (typeof value === "string" && value !=""); // had to also check for empty array values, which are also strings
  }

Logger.log(filteredValues); // [only the string values from the worksheet]
}

I was having a similar problem, and stumbled across the flat() method for flattening a [[1,2,3]] array to [1,2,3]. Sure enough, not only did flat() take the 2 dim array of objects returned by getvalues(), but it reconstituted the objects back into proper numbers and strings! Huzzah!

Screenshot of sheet data
enter image description here
Here's my test script:

function listOflists (){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

// Load data from the spreadsheet.
// display data array
var DeckID = spreadsheet.getRange("B2:B50").getValues();
Logger.log(DeckID); // [[2D array]]

// First attempt to filter out desired elements
var values = DeckID
var filteredValues = values.filter(isString);

  function isString(value) {
  Logger.log(value + " is an " + typeof value); // Everything is an object !
  return typeof value === "string"; // which renders this comparison useless
  }

Logger.log(filteredValues); // null result

// Revised attempt to filter out desired elements
// by first using the flat method on the 2D array
var values = DeckID.flat(); 
Logger.log(values); // [1D array]


var filteredValues = values.filter(isString);

  function isString(value) {
  Logger.log(value + " is an " + typeof value);
  return (typeof value === "string" && value !=""); // had to also check for empty array values, which are also strings
  }

Logger.log(filteredValues); // [only the string values from the worksheet]
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文