有没有 "var = " 的变量可以吗?

Is it ok to have variables without "var = "?

此脚本似乎运行良好。这个问题更针对它是怎么写的(初学者)。

我一直在处理一个脚本,在将它分解成多个函数后,我很难将变量从第一个函数传递到下一个函数。仔细阅读后,我发现我不一定 需要 包括 "var = ",虽然我不是 100% 确定有什么区别。我设法让 "variables"(它们仍然被认为是变量吗?)传递给以下函数,但我只是想确保我所做的是 efficient/acceptable.

function onEdit(e){
  /*  I switched these from "var = " because they weren't passing
  down to the following functions.
  */
  activess = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  activeCell = activess.getActiveCell();
  valueToFind = activeCell.getValue();
  //  Column Values
  foundItemValues = [];
  foundSubItemValues = [];
  foundCatValues = [];
  foundSubCatValues = [];

  //  These never change regardless of active sheet
  catss = SpreadsheetApp.getActive().getSheetByName('Categories-Concat');
  catData = catss.getRange(1,2,catss.getLastRow(),catss.getLastColumn()).getValues();
  catIndex = catData[0].indexOf(activeCell.getValue()) + 2;
  subCatIndex = catData[0].indexOf(activeCell.getValue()) + 2;

  itemss = SpreadsheetApp.getActive().getSheetByName('Items');
  itemdata = itemss.getRange(2,1,itemss.getLastRow(),4).getValues();

  if(e.range.getSheet().getName() == 'projectSelections'){  
    activess = e.range.getSheet().getName();
    colCss = SpreadsheetApp.getActive().getSheetByName('Categories-Concat');
    colCdata = colCss.getRange(1,2,1,colCss.getLastColumn()).getValues();
    colCIndex = colCdata[0].indexOf(activeCell.getValue()) + 2;

    if(activeCell.getColumn() == 2 && activeCell.getRow() > 1){
      this.subCategoryDV(e);
    }
  }
}


function subCategoryDV(e){
  //  Populate SUB-CATEGORY data validations
  activeCell.offset(0, 1).clearDataValidations();
  for (var q = 1; q < catData.length; q++){
    for(var i=0;i<catData.length;i++){ 
      if(valueToFind==catData[0][i]){
        foundSubCatValues.push(catData[q][i]);
      }
    }
  }
  var subCatValidationRange = foundSubCatValues;
  var subCatValidationRule = SpreadsheetApp.newDataValidation().requireValueInList(subCatValidationRange).build();
  if(activeCell.getValue() != ""){ 
    activeCell.offset(0, 1).setDataValidation(subCatValidationRule);
  }
}      

关键字var确保变量保持在本地范围内(大致上,只有变量所在的函数才能看到它。)见这里:What is the purpose of the var keyword and when should I use it (or omit it)?

一般来说,尝试将事物保持在本地是一种很好的做法 - 全局变量存在很多问题,快速 google 搜索一下为什么全局变量或邪恶(或类似的东西)会告诉你所有问题关于它。

如果您尝试使用第二个函数,则需要传递引用的每个变量 - activeCellcatDatavalueToFindfoundSubCatValues,沿着边 'e'.

您可以做的另一件事是在函数 onEdit.

中定义函数 subCategoryDV