请使用以下字符串:
/foo/1/bar/2/cat/bob
我需要将其解析为最终为的对象或数组:
foo = 1
bar = 2
cat = bob
答案 0 :(得分:5)
if 'users input' in (command = to left):
Left_new = input("How many places would you like to move left")))
elif 'users input' in (command = right):
Right_new = input("How many places would you like to move right")))
elif 'users input' in (= to up):
up_new = input("How many places would you like to move up")))
elif 'users input' in (= down ):
Down_new =input("How many places would you like to move down")))
else:
if ( users input <9) or ( users input > 100 ):
print("Sorry one of your inputs were invalid...")
&#13;
答案 1 :(得分:2)
const str = '/foo/1/bar/2/cat/bob/test/'
const parts = str.split('/')
.filter(val => val !== '')
const obj = {}
for (let ii = 0; ii < parts.length; ii+=2) {
const key = parts[ii]
const value = parts[ii+1]
obj[key] = !isNaN(value) ? Number(value) : value
}
console.log(obj)
&#13;
答案 2 :(得分:1)
正则表达式是各种解析的首选工具:
str = '/foo/1/bar/2/cat/bob'
obj = {};
str.replace(/(\w+)\/(\w+)/g, (...m) => obj[m[1]] = m[2]);
console.log(obj);
&#13;
答案 3 :(得分:0)
只为了它的乐趣,
let str = "/foo/1/bar/2/cat/bob",
arr = str.split("/"),
obj = {};
arr.shift();
while (arr.length) obj[arr.shift()] = arr.shift();