輸入:
/家/Ubuntu
輸出:
[
{"name":"/","path":"/"},
{"name":"home",path:"/home"},
{"name":"ubuntu",path:"/home/ubuntu"}
]
怎么會這樣?
uj5u.com熱心網友回復:
我想這就是你需要的:
getTree = (path, nodes = []) => {
// Split by levels
const parts = path.split('/')
// Remove last node from path and add to nodes array
nodes.push({ name: parts.pop(), path })
// Update path without last node (already added)
path = parts.join('/')
if (path.length) {
// Recall method recursively if nodes left
return getTree(path, nodes)
} else {
// Or add root node to array and return it
nodes.push({ name: '/', path: '/' })
return nodes
}
}
用法:
const path = '/root/user/home/ubuntu'
console.log(getTree(path))
輸出:
[
{name: 'ubuntu', path: '/root/user/home/ubuntu'}
{name: 'home', path: '/root/user/home'}
{name: 'user', path: '/root/user'}
{name: 'root', path: '/root'}
{name: '/', path: '/'}
]
uj5u.com熱心網友回復:
如果我正確理解你的問題,你可以做這樣的事情
通過使用Array.prototype.split()將路徑分成幾部分,并將第一個引數(基數)設定為家,將其余引數設定為結果路徑
const string = 'home/ubuntu/test';
console.log(parse(string));
console.log(parse('home/'));
console.log(parse('/'));
function parse(str) {
const obj = {};
const strArr = str.split('/');
obj['home'] = strArr[0] ? strArr[0] : '/';
const path = strArr.slice(1, strArr.length).join('/');
obj['path'] = path ? path : '/';
return obj;
}
PS如果這不是你的意思,請在評論中告訴我
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345105.html
標籤:javascript 小路
