该脚本工作正常,但在 'google-apps-script' 中不正常

The script is working fine, but not in 'google-apps-script'

function main() {

    var data = [['test1', 'element1', 'price1'], ['', 'element2', 'price2'], ['', 'element3', 'price3'], ['','' ,'' ], ['test2', 'anotherele1', 'anotherprice1'], ['', 'anotherele2', 'anotherprice2'], ['', 'anotherele3', 'anotherprice3'], ['', '', ''], ['test3', 'aaa', 123.0], ['', 'bbb', 345.0], ['', 'ccc', 678.0], ['', '', ''], ['','' , '']]

    var test = parseData(data)
    Logger.log(test)
}


function isBlank(line) {
    return line[0].trim() === '' && line[1].trim() === '';
}


function parseData(data) {

    const output = {};
    let currentGroupName = '';

    data.forEach(line => {
        if (isBlank(line)){
            return; 
        }

        if (line[0].trim().length > 0) {
            currentGroupName = line[0].trim();
        }

        output[currentGroupName] = output[currentGroupName] || {};

        output[currentGroupName][line[1]] = line[2];
    });

    return output;
}

以下 JS 脚本在我 运行 我的计算机上运行时运行良好。但是,如果我尝试在 Adwords 上将 运行 作为 Preview(类似于 Adwords 控制台),我会收到语法错误 Syntax errors in script: Missing ; before statement. (line 23)。请注意,第 23 行只是 let currentGroupName = '';。有没有一种干净的方法来解决这个问题?此代码适用于在您自己的计算机上以及使用 google-apps-scripts 进行测试。

这是我的问题的图片:

如果您想在 Google Apps 脚本中使用此脚本,let 并且无法使用箭头运算符。那么下面的修改呢?

修改点:

  1. let 替换为 var
  2. data.forEach(line => { 替换为 data.forEach(function(line){

修改脚本:

function main() {
    var data = [['test1', 'element1', 'price1'], ['', 'element2', 'price2'], ['', 'element3', 'price3'], ['','' ,'' ], ['test2', 'anotherele1', 'anotherprice1'], ['', 'anotherele2', 'anotherprice2'], ['', 'anotherele3', 'anotherprice3'], ['', '', ''], ['test3', 'aaa', 123.0], ['', 'bbb', 345.0], ['', 'ccc', 678.0], ['', '', ''], ['','' , '']]
    var test = parseData(data)
    Logger.log(test)
}

function isBlank(line) {
    return line[0].trim() === '' && line[1].trim() === '';
}

function parseData(data) {
    const output = {};
    var currentGroupName = '';
    data.forEach(function(line){
        if (isBlank(line)){
            return; 
        }
        if (line[0].trim().length > 0) {
            currentGroupName = line[0].trim();
        }
        output[currentGroupName] = output[currentGroupName] || {};
        output[currentGroupName][line[1]] = line[2];
    });
    return output;
}

结果:

{
  "test1": {
    "element1": "price1",
    "element2": "price2",
    "element3": "price3"
  },
  "test2": {
    "anotherele1": "anotherprice1",
    "anotherele2": "anotherprice2",
    "anotherele3": "anotherprice3"
  },
  "test3": {
    "aaa": 123,
    "bbb": 345,
    "ccc": 678
  }
}

参考:

如果我误解了你的问题,我很抱歉。

Tanaike 的解决方案应该可以解决您的问题。但请允许我添加更多背景信息。 Google Apps Script 自 2009 年以来一直存在,它是 Ecmascript 5 的实现。let 语句和箭头运算符仅在 Ecmascript 6 及更高版本中受支持。

Google 的问题跟踪器上有一个 App Script 支持 EcmaScript 6 的功能请求。 Apps Script 社区中的许多人一直在呼吁支持 Ecmascript 6。您可以通过给问题加注星标来表达您的意见。

这是一个 link: https://issuetracker.google.com/issues/36764074