【问题标题】:How to get indexes of specific array elements in Apps script如何在 Apps 脚本中获取特定数组元素的索引
【发布时间】:2019-03-09 18:25:17
【问题描述】:

使用我拥有的应用程序脚本:

var conversation = [R: test1 ,  R: test3 ,  tx ,  I sent ]

我想获取包含“R:”的元素的索引列表,所以我尝试了

var replies = conversation.map(function(message) { 
    message.indexOf('R:')!== -1 && return conversation.indexOf(message);

});  

但现在我无法保存函数,并且出现语法错误。我做错了什么?

【问题讨论】:

    标签: javascript google-apps-script


    【解决方案1】:

    您可以在找到R: 的位置使用reduce 并继续推送索引

    var conversations = ['R: test1' ,'R: test3','tx','I sent' ]
    
    var replies = conversations.reduce(function(op,message,index) {
        if(message.indexOf('R:')!== -1) {
          op.push(index)
        }
        return op
    },[]);  
    
    console.log(replies)

    【讨论】:

      【解决方案2】:

      两件事:

      1. 您不能仅使用 map 来做到这一点。
      2. 您的return 放错了位置,这是语法错误的原因。

      要一次性完成,最简单的方法是使用forEachpush(因为Apps 脚本不支持for-of):

      var replies = [];
      conversation.forEach(function(message, index) {
          if (message.indexOf("R:") !== -1) {
              replies.push(index);
          }
      });
      

      但您可以使用mapfilter 分两次完成:

      var replies = conversation
          .map(function(message, index) {
              return message.indexOf("R:") !== -1 ? index : -1;
          })
          .filter(function(index) {
              return index !== -1;
          });
      

      【讨论】:

      • 谢谢 - 我决定使用 reduce,因为我以前从未使用过它。感谢您的解释。
      • @user61629 - 不用担心!仅供参考,当累加器从不改变时使用reduce(在这种情况下,它总是相同的数组)有时被认为是糟糕的风格。不过,这很常见。并不是说您应该更改您接受的答案(请不要),只是要注意reduce 的主要用例是诸如总和之类的东西,其中累加器不断变化。例如:[1, 2, 3, 4].reduce(function(s, n) { return s + n; }, 0);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      相关资源
      最近更新 更多