Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google apps script 在google电子表格上,如何仅使用返回数组的函数的某个值?_Google Apps Script_Google Sheets - Fatal编程技术网

Google apps script 在google电子表格上,如何仅使用返回数组的函数的某个值?

Google apps script 在google电子表格上,如何仅使用返回数组的函数的某个值?,google-apps-script,google-sheets,Google Apps Script,Google Sheets,如果我有这样的功能: function returnAnArray() { return [1, 2, 3, 4, 5]; } function returnAnArray(index) { var arrayOfNums = [1, 2, 3, 4, 5]; // if true, return single element of array if (index != null || index != undefined) return arrayOfNum

如果我有这样的功能:

function returnAnArray() {
  return [1, 2, 3, 4, 5];
}
function returnAnArray(index) {
   var arrayOfNums = [1, 2, 3, 4, 5];

   // if true, return single element of array
   if (index != null || index != undefined)
     return arrayOfNums[index];

   // else, return whole array
   return arrayOfNums;
}
在电子表格上,如果我使用
=RETURNANARRAY()
,它将填充包含数组值的5行。如果我只想使用数组的第一个或n个值,我需要在电子表格上使用什么语法

试试这个:

function returnAnArray(index) {
   var arrayOfNums = [1, 2, 3, 4, 5];
   return arrayOfNums[index];
}
然后使用公式
=returnAnArray(validIndexInArray)

更新:

我想和大家分享我发现的其他一些东西

有时,对于同一个函数,您可能希望返回一个数组或仅返回数组的一个元素,您可以这样合并它:

function returnAnArray() {
  return [1, 2, 3, 4, 5];
}
function returnAnArray(index) {
   var arrayOfNums = [1, 2, 3, 4, 5];

   // if true, return single element of array
   if (index != null || index != undefined)
     return arrayOfNums[index];

   // else, return whole array
   return arrayOfNums;
}
使用
=returnAnArray()
将返回整个数组,而
=returnAnArray(index)
将返回数组中的单个元素

或者,您可以像这样使用内置公式索引:
=INDEX(returnAnArray(),INDEX)


这将使您能够从二维数组中检索单个元素,该数组也可以通过附加参数内置到自定义函数中。

使用内置索引函数

示例
在单元格
A2
中填写所需的项目编号,然后在A3中填写以下公式:

=INDEX(returnAnArray(),A2)