TypeError: Cannot find function When using Array.p

2019-09-08 05:57发布

问题:

I have a very simple function I am trying to add to an array. I have seen examples on this site where people have extended different simple items, like String & Array. But I also have seen comments where Google doesn't allow you to extend certain classes. But from what I can tell, that was only for custom Google classes, like Spreadsheet, Range, etc.

Why is this throwing a TypeError? Tried to use the same function I found here.

Array.prototype.findIndex = function(search){
  if(search == "") return false;
  for (var i=0; i<this.length; i++)
    if (this[i] == search) return i;

  return -1;
} 

//Do a search on a specific range, find the correct ID, and do a lookup based on ID
function onEdit(e) {
  var e = {};
  e.value = "Test String";
  var client = e.value;
  var columnValues = mydoc.getRangeByName(categoryRangeName).getValues();

  //columnValues returns 2D array of values
  //https://developers.google.com/apps-script/reference/spreadsheet/range#getValues()
  var searchResult = columnValues.findIndex(e.value);  //**ERROR HERE**

}

UPDATE

I will also add, that I set the method to just return a value like this just to test that there was no problem with the prototype, and it failed on the same error.

Array.prototype.findIndex = function(val) {
  return val;
} 

And I created a function with the same for loop, and it works just fine.

function findIndex(vals, search) {
  if(search == "") return false;
  for (var i=0; i<vals.length; i++)
    if (vals[i] == search) return i;

  return -1;
}

回答1:

The findIndex function, search on a 1D array, however, you have a 2D array. You must change the findIndex function to search on a 2D array.

Array.prototype.findIndex = function(search) {
  if(search === '') return false;
  for (var i = 0, len = this.length; i < len; i++)
    if (this[i] === search) return i;
  return -1;
}

function onEdit(e) {
  var search_text = 'Test String';
  var columnValues1D = ['String Test', 'Test String'];
  var columnValues2D = [['String Test'], ['Test String']];
  Logger.log(columnValues1D.findIndex(search_text)); // <-- 1
  Logger.log(columnValues2D[0].findIndex(search_text)); // <-- -1
  Logger.log(columnValues2D[1].findIndex(search_text)); // <-- 0
}

UPDATE

Array.prototype.findIndex = function(search) {
  if(search === '') return false;
  for (var i = 0, len = this.length; i < len; i++)
    if (this[i][0] === search) return i;
  return -1;
}

function onEdit(e) {
  var search_text = 'Test String';
  var columnValues2D = [['String Test'], ['Test String']];
  Logger.log(columnValues2D.findIndex(search_text)); // <-- 1
}