【问题标题】:For loop and If statement in a list google apps script列表谷歌应用程序脚本中的 For 循环和 If 语句
【发布时间】:2022-01-25 00:02:31
【问题描述】:

我对 python 很友好,但我需要在谷歌应用脚​​本中使用相同的代码。 (代码在正文下方)

提前谢谢你

我需要这样的输出:

plus = [[600, 'ter', 'simple'], [600, 'ter', 'simple']]

这是我的代码:

      function myFunction() {
  
          var data =[[600, 'ter', 'simple'], [600, 'ter', 'simple'], [300, 'ter', 'medium'], [200, 'ter', 'Hard']]

          var plus  = []

          for (let i = data[0]; i < data.leng; i++)
          {
            if ( data[i][0] == data[0][0])
            {
              plus.push(data)
            }
          }
        }

【问题讨论】:

  • Google Apps 脚本 (js) 中没有您需要使用像 [[], []] 这样格式的二维数组的元组。
  • 来自javascript tag info:“[JavaScript] 与 Java 编程语言无关,只有表面上的相似之处。...”
  • 非常感谢@Turing85,我已经编辑了我的消息
  • 您只需将最后一行修改为plus.push(data[i])。另见stackoverflow.com/questions/63720612/…

标签: javascript for-loop if-statement google-apps-script


【解决方案1】:

这里和那里有几个语法错误。在代码中指出它们:

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
function myFunction() {
  var data = [
    [600, 'ter', 'simple'],
    [600, 'ter', 'simple'],
    [300, 'ter', 'medium'],
    [200, 'ter', 'Hard'],
  ];
  var plus = [];
  for (
    let i = 0 /* intializer or counter should start with 0 not data[0]  */;
    i < data.length /* No property named leng data.leng */;
    i++
  ) {
    if (data[i][0] == data[0][0]) {
      plus.push(
        data[
          i
        ] /* push only the current element  `data[i]` and not the full `data` array */
      );
    }
  }
  console.log(plus);
}
myFunction();
&lt;!-- https://meta.stackoverflow.com/a/375985/ --&gt;    &lt;script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 很高兴你在这个论坛@theMaster,非常感谢你的代码和评论,这对我理解很多基础知识很有帮助。我总是向你学习,你是最棒的。
【解决方案2】:

使用Array.filter(),像这样:

function filterData() {
  const data = [
    [600, 'ter', 'simple'],
    [600, 'ter', 'simple'],
    [300, 'ter', 'medium'],
    [200, 'ter', 'Hard'],
  ];
  const filterBy = { column: 0, value: data[0][0] };
  return data.filter(row => row[filterBy.column] === filterBy.value);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2017-01-15
    相关资源
    最近更新 更多