我需要将数组 A 更改为类似于数组 B,确保散列项成为任意数量的非散列项之前,直到下一个散列项
const A = [ '# test',
'test',
'# layouts',
'main',
'nav' ]
const B = ['test/test',
'layouts/main',
'layouts/nav' ]
最佳答案
您可以使用reduce
来实现此目的,累加器应该是一个包含两个值的对象,第一个是结果数组,另一个是要在中使用的当前哈希字符串reduce
生成路径。一旦reduce
完成工作,我们就可以将累加器的result
属性存储到我们的结果变量B
中:
const B = A.reduce((acc, str) => { // for each string in the array A
if(str.indexOf("#") === 0) { // if the string is hashed one
acc.currentHash = str.slice(2); // set the current hash to this string
} else { // otherwise
acc.result.push(acc.currentHash + "/" + str); // use the current hash to generate the resulting string of the current string
}
return acc;
}, { result: [], currentHash: ""}).result; // once reduce finishes, use '.result' to access the result array of the accumulator
示例:
const A = [ '# test', 'test', '# layouts', 'main', 'nav' ];
const B = A.reduce((acc, str) => {
if(str.indexOf("#") === 0) {
acc.currentHash = str.slice(2);
} else {
acc.result.push(acc.currentHash + "/" + str);
}
return acc;
}, { result: [], currentHash: ""}).result;
console.log(B);
关于javascript - 如何使用同一数组中的其他项目更改数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53732337/