创造所有可能性的功能

时间:2018-10-22 14:09:09

标签: javascript

var parameter1 = "String";

var parameter 2 = "-";

function test(parameter1, parameter2) 

var parameter1 =“ String”;

var参数2 =“-”;

功能测试(参数1,参数2)

结果:

字符串

S-tring

S型环

S-t-r-ing

S-t-r-i-ng

S-t-r-i-n-g

S-t-r-in-g

S-t-ri-ng

S-t-ri-n-g

S-t-rin-g

S-tr-ing

S-tr-i-ng

S-tr-i-n-g

S-tr-in-g

S-tri-ng

S-tri-n-g

S-trin-g

指环

St-r-ing

St-r-i-ng

St-r-i-n-g

St-r-in-g

St-ri-ng

St-ri-n-g

St-rin-g

拉伸

Str-i-ng

Str-i-n-g

Str-in-g

Stri-ng

Stri-n-g

Strin-g

**到目前为止,您一直在尝试实现此结果,但是没有任何效果,因此对此表示感谢。谢谢 ** 我尝试过这种方式,但我想获得与上述结果完全相同的输出

     var array1=["S","T","R","I","N","G"];
      var array2=["-"];
     combos = [] //or combos = new Array(2);

     for(var i = 0; i < array1.length; i++)
    {
     for(var j = 0; j < array2.length; j++)
     {


        combos.push(array1[i] + array2[j])
     }
  console.log(combos);
}

1 个答案:

答案 0 :(得分:0)

您可以使用生成器来获取字符串的一部分,并通过检查右侧是否有要分割的字符来迭代此值。如果是这种情况,请使用该字符串再次调用该函数,并为结果集映射新的对。

function* split(string) {
    var i = 0;
    while (++i < string.length) {
        yield [string.slice(0, i), string.slice(i)];
    }
}

function fn(string, delimiter) {
    const join = l => r => [l, r].join(delimiter);
    var result = [string],
        parts;
    for (var [left, right] of split(string)) {
        parts = join(left);
        if (right.length > 1) {
            result.push(...fn(right, delimiter).map(parts));
        } else {
            result.push(parts(right));
        }
    }
    return result;
}

console.log(fn('String', '-'));
.as-console-wrapper { max-height: 100% !important; top: 0; }