在JavaScript中将一个路径划分为多个完整路径



我试图从一个路径中找到一个"完整"路径数组的最佳方法。

输入:

'source/folder/folder2/folder3/file'

我想要这个输出:

[
'/',
'/folder',
'/folder/folder2',
'/folder/folder2/folder3',
'/folder/folder2/folder3/file'
]

目前,我可以看到我的代码没有优化:

pathArray = path.split('/');
if (pathArray [0] === '') {
pathArray .shift();
}
if (pathArray [pathArray .length - 1] === '') {
pathArray .pop();
}
const finalArrayPath = [];
for (let i = 0; i < pathArray.length; i++) {
let path = '';
for (let j = 0; j <= i; j++) {
path = path + pathArray[j] + '/';
}
finalArrayPath.push(path);
}

更重要的是,我的代码在每个路径的末尾都有一个/,在开头有一个源代码,我可以添加代码来删除这些代码,但我想要一个更优化的代码。

使用Array.prototype.reduce方法可以执行以下操作:

const path = "source/folder/folder2/folder3/file";
const result = path.split("/").slice(1).reduce((allPaths, subPath) => {
const lastPath = allPaths[allPaths.length-1];
allPaths.push(lastPath.endsWith("/") ? (lastPath + subPath) : `${lastPath}/${subPath}`);
return allPaths;
}, ["/"]);
console.log(result)

使用单个for循环。。。

const path = 'source/folder/folder2/folder3/file';
const [root, ...pathArr] = path.split('/');
const paths = [];
for (let i = 0; i <= pathArr.length; i++) {
paths.push(`/${pathArr.slice(0, i).join('/')}`);
}
console.log('root: ', root);
console.log('paths: ', paths);

或者使用Array.from()。。。

const path = 'source/folder/folder2/folder3/file';
const [root, ...pathArr] = path.split('/');
const paths = Array.from(
{ length: pathArr.length + 1 },
(_, i) => `/${pathArr.slice(0, i).join('/')}`
);
console.log('root: ', root);
console.log('paths: ', paths);

最新更新