已知一个对象
const data = {
age: 1,
person: [
{ name: "bdd", date: "44444" },
{ name: "b222dd", date: "666" }
]
}
现在提供模板
const expression = "{{person.name}}###{{person.date}}"
应该如何编写函数能输出以下字符串?
bdd###444,b222dd#666
已知一个对象
const data = {
age: 1,
person: [
{ name: "bdd", date: "44444" },
{ name: "b222dd", date: "666" }
]
}
现在提供模板
const expression = "{{person.name}}###{{person.date}}"
应该如何编写函数能输出以下字符串?
bdd###444,b222dd#666
const data = {
age: 1,
person: [
{ name: "bdd", date: "444" },
{ name: "b22dd", date: "666" },
]
}
const expression = "{{person.name}}###{{person.date}}"
const tpl = (s, d) => {
const mem = []
let len, j = 0
const t = s.replace(/\{\{(.+?)\}\}/g, (_, p) => {
const v = p.trim().split(".").reduce((a, v) => {
if (! a) return console.error(`{{${p}}} is null before "${v}"`)
if (a instanceof Array) {
const c = a.map(o => o[v])
len = c.length
return c
}
return a[v]
}, d)
mem[j] = v
return `@@${j ++}@@`
})
console.log(mem)
return Array.from({ length: len }, (_, i) => t.replace(/@@(\d+)@@/g, (_, j) => mem[j] instanceof Array ? mem[j][i] : mem[j]))
}
console.log(tpl(expression, data).join(","))
8 回答4.5k 阅读✓ 已解决
6 回答3.1k 阅读✓ 已解决
5 回答2.7k 阅读✓ 已解决
6 回答2.3k 阅读
5 回答6.2k 阅读✓ 已解决
4 回答2.2k 阅读✓ 已解决
3 回答2.4k 阅读
person 是一个数组。
https://segmentfault.com/q/10...