简体   繁体   English

javascript(Google Apps脚本)声明变量

[英]javascript (google apps script) declaring variables

I have written a code. 我已经写了代码。 To run the code I have declared quite a few variables. 为了运行代码,我声明了很多变量。 Now that I finished, I realised that I did not have to declare the variables as I can call on what the variable is supposed to call for directly within the function. 现在我完成了,我意识到我不必声明变量了,因为我可以在函数中直接调用该变量应该调用的内容。

Example: 例:

function test() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var date = Utilities.formatDate(new Date(), "GMT", "dd-MMM-yyyy");
  sheet.appendRow(date);
}

I could have not declared date and written this: 我本来不能声明日期并写成这样:

function test() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  sheet.appendRow(Utilities.formatDate(new Date(), "GMT", "dd-MMM-yyyy"));
}

Which of those is considered best practice and better for performance of app? 哪一种被认为是最佳实践,并且对应用程序的性能更好?

Thanks 谢谢

The effect on performance will be negligible. 对性能的影响可以忽略不计。 You should write it the way that is most readable. 您应该以最易读的方式编写它。 In your case that is debatable, but I like declaring the date variable since it makes the subsequent line much shorter and less overwhelming. 在您的情况下,这值得商bat,但我喜欢声明date变量,因为它使随后的行更短并且不那么令人费解。

A case where it could affect performance would be if you were consuming the date in multiple locations. 如果您在多个位置使用日期,可能会影响性能。 Then, you would want to declare a variable. 然后,您需要声明一个变量。 For example... 例如...

function test() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  sheet.appendRow(Utilities.formatDate(new Date(), "GMT", "dd-MMM-yyyy"));
  somethingElse(Utilities.formatDate(new Date(), "GMT", "dd-MMM-yyyy"));
}

Aside from violating the DRY principle , the above hurts performance because you are doing the work twice (creating a Date object and formatting it). 除了违反DRY原则之外 ,上述内容还会影响性能,因为您要进行两次工作(创建Date对象并对其进行格式化)。

In summary, if you are only consuming the value once, you don't need to make it a variable, but you should if it improves readability. 总而言之,如果只使用一次该值,则无需将其设为变量,但是如果它可以提高可读性,则应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM