简体   繁体   中英

How to test type of range parameter in Google Spreadsheet script?

I'm just starting tinkering with scripts for Google Spreadsheet and I have a problem :

How to test if the type of a function's parameter is a range of cells ?

I'd like to do something like this :

if(typeof intput != "range") {
  throw "input must be a range";
}

From Google's examples here (middle of the page) :

if (typeof inNum != "number") {  // check to make sure input is a number
  throw "input must be a number";  // throw an exception with the error message
} 

So this seems to be the right way to test the type of a variable. But I don't know how to test if the type is a range of cells.

It'd be even better if I could specify if the range is one or two dimensions.

A range of cells is just a Array (multidimensional array) Javascript has a problem in that way. Array's are seen as an object. So first check if you have the "object" type and then you could test like this.

if(typeof intput=="object"&&intput.length!=undefined) {
  //input is a array
}else{
  //Not a array
}

By testing a default property you can determine for certain that you have a array

A range may represent a single cell (eg 'A1' ) or group of cells (eg 'A1:A2' ).

A range is converted into a range value when it is passed as a custom function parameter (eg =processRangeVal(A1:A2) ).

If the range is a single cell then the range value is simply the data in that cell.

If the range is a group of cells then the range value is a 2-dimensional array. The first dimension is the rows and the second dimension the columns in each row.

To test for the range value representing a cell vs a group of cells:

function processRangeVal(rangeVal) {
  if (Array.isArray(rangeVal[0])) {
    // do 2d-array handling
  } else {
    // do cell data handling
  }
} 

rangeVal[0] resolves to undefined if the range is a single cell and the cell data does not support indexing. In this case Array.isArray(undefined) resolves to false which is what we want.

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