目的: 执行 EL 表达式
场景
- 环境作用域 {a:1,b:{a:1},c:[{a:1},{b:2}]}
${a}=>1
${a===1}=>false
${a===1 ?'是':'否'} => 是
${b}=>{a:1}
${c}=>[{a:1},{b:2}]
方案1:模板字符串 不满足
- 模板字符串,最终返回的字符串 ,不能满足我们的诉求
方案2:自定义作用域链,执行返回
function toData(inStr, data) {
const names = JSON.stringify(Object.keys(data)).replace(/"/g, '');
const values = JSON.stringify(Object.values(data));
const str = inStr.replace(/\$\{(.+?)\}/g, '').trim();
const isStr = str.length > 0;
if (isStr) {
const computed = inStr.replace(/\$\{(.+?)\}/g, function (match, key) {
let result;
eval(` var ${names} = ${values}; result = eval((${key})); `);
return result||"";
});
return computed;
}
let result;
inStr.replace(/\$\{(.+?)\}/g, function (match, key) {
eval(`
var ${names} = ${values};
debugger;
result =JSON.stringify({
res:eval((${key}))
});
`);
});
return JSON.parse(result).res;
}
const data = { name: 123, age: 11, b: { c: 123 }, d: [{ a: 1, b: 2 }], }
console.log( toData('${name == 1?"8989":"999"}',data), );
console.log( toData('${b}',data), );
console.log( toData('${d}',data), );
最后
- 思考
- with 处理 优缺点
- eval or Function 处理的优缺点
- 怎么自定义作用域 走其他的方案
- … 啊 想不到了