【问题标题】:Concat array elements into new array将数组元素连接到新数组中
【发布时间】:2021-02-12 08:27:07
【问题描述】:

我有一个由"/" 分隔的字符串,然后我将其拆分为一个数组。例如。

local string = 'Code/Github/Exercises'
local array = std.split(string, "/")

// ['Code', 'Github', 'Exercises']

然后我如何转换array 以便获得输出:

// ['Code', 'Code/Github', 'Code/Github/Exercises']

【问题讨论】:

    标签: arrays jsonnet


    【解决方案1】:

    下面sn-p实现它,使用std.foldl()作为“迭代器”访问每个元素并构建返回数组

    local string = 'Code/Github/Exercises';
    local array = std.split(string, '/');
    
    
    // If `array` length > 0 then add `elem` to last `array` element (with `sep`),
    // else return `elem`
    local add_to_last(array, sep, elem) = (
      local len = std.length(array);
      if len > 0 then array[len - 1] + sep + elem else elem
    );
    
    // Accumulate array elements, using std.foldl() to visit each elem and build returned array
    local concat(array) = (std.foldl(function(x, y) (x + [add_to_last(x, '/', y)]), array, []));
    
    concat(array)
    

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 2011-11-03
      • 2020-06-22
      • 2013-02-04
      相关资源
      最近更新 更多