Simple Javascript code not working in Google docs due to arrow function

前端 未结 2 2024
独厮守ぢ
独厮守ぢ 2021-01-29 10:29

I have tried implementing a piece of simple code as a script in google docs. It\'s function is validating ID numbers. The problem is that the syntax used for this code is too ad

相关标签:
2条回答
  • 2021-01-29 11:07

    Edit: Arrow functions are currently supported with the V8 engine. See: https://developers.google.com/apps-script/guides/v8-runtime#arrow_functions

    Google Apps Script (GAS) doesn't support ECMAScript 2015 (ES6) yet. Unfortunately, in the current stage, the functions which was added from ES6 cannot be used. So it is required to convert such functions for GAS. In your script, also such functions are used. So how about this modification?

    Modification points :

    • Arrow function cannot be used at GAS.
      • This was mentioned by CertainPerformance and NielsNet.
    • Array.from() cannot be used at GAS.
      • Here, I used Array.map().

    Modified script :

    function isValidIsraeliID(id) {
      var id = String(id).trim();
      if (id.length > 9 || id.length < 5 || isNaN(id)) return false;
    
      // Pad string with zeros up to 9 digits
      id = id.length < 9 ? ("00000000" + id).slice(-9) : id;
    
      return Array.map(id, Number) // Modified
      .reduce(function(counter, digit, i) { // Modified
        const step = digit * ((i % 2) + 1);
        return counter + (step > 9 ? step - 9 : step);
      }) % 10 === 0;
    }
    

    References :

    • Built-in Google Services: Basic JavaScript features
    • Arrow functions
    • Array.from()
    • Array.prototype.map()

    If this result was not what you want, please tell me. I would like to modify it.

    0 讨论(0)
  • 2021-01-29 11:22

    Just replace the arrow function with a function:

    .reduce(function(counter, digit, i) {
    
    0 讨论(0)
提交回复
热议问题