【问题标题】:Replace keywords in an array of strings with previous elements up to a specific one用前面的元素替换字符串数组中的关键字,直到特定的元素
【发布时间】:2021-02-11 08:47:05
【问题描述】:

我有一个包含以下元素的字符串数组:

2+2
3+3

sum

# Example comment
5+5

3+2

sum

# Random word
10-5
sum

我想用 + 分隔之前的元素替换每个单词 sum,但最多是最近的评论(例如 # Example comment)。所以对于上面的数组输出应该是:

2+2
3+3

2+2+3+3

# Example comment
5+5

3+2

5+5+3+2

# Random word
10-5
10-5

请注意,第一个“块”没有注释,因为它位于数组的开头,但它仍然可以正常工作。实现这种结果的最佳方法是什么?

【问题讨论】:

    标签: javascript arrays string loops ecmascript-6


    【解决方案1】:

    您可以使用 for-loop 执行此操作,同时使用数组保存项目直到到达评论(这种情况下我们将清空它并继续):

    const arr = [
      "2+2",
      "3+3",
    
      "sum",
    
      "# Example comment",
    
      "5+5",
      "3+2",
    
      "sum",
    
      "# Random word",
    
      "10-5",
      
      "sum"
    ];
    
    let items = [];
    
    for(let i = 0; i < arr.length; i++){
      const item = arr[i];
      if(item === "sum") arr[i] = items.join("+");
      else if(item.startsWith("#")) items = [];
      else items.push(item);
    }
    
    console.log(arr);

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 2017-05-14
      • 2015-11-19
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多