我有2个字符串
[a,b,c] //there could be any number of items in these 2 strings
[x,y,z]
我想要一个像这样的输出
a[x,y,z]
b[x,y,z]
c[x,y,z]
无法获得输出的逻辑。
答案 0 :(得分:2)
要使用 map()
var s1 = '[a,b,c]',
s2 = '[x,y,z]';
console.log(
s1
.slice(1, -1) // remove the `[` and `]`
.split(',') // split based on `,`
.map(function(a) { // iterate and generate array
return a + s2;
})
)
要使用 reduce()
var s1 = '[a,b,c]',
s2 = '[x,y,z]';
console.log(
s1
.slice(1, -1) // remove `[` and `]`
.split(',') // split based on `,`
.reduce(function(a, b) { // iterate and generate string
return a + (a.length ? '\n' : ' ') + b + s2;
}, '')
)
答案 1 :(得分:0)
<?php
$s1 = '[a,b,c]';
$s2 = '[x,y,z]';
$items = explode(',', trim($s1, '[]'));
foreach ($items as $item) {
echo($item . $s2 . "\n");
}
答案 2 :(得分:0)
使用String.slice
和String.replace
函数的解决方案:
var keys = '[a,b,c,d,e]', values = '[x,y,z]',
output = keys.slice(1, -1).replace(/([a-z]),?/g, function(m, p1){
return p1 + values + "\n";
});
console.log(output);
输出:
a[x,y,z]
b[x,y,z]
c[x,y,z]
d[x,y,z]
e[x,y,z]