js面试题,模板字符串替换

结构:t="<ul><li>${name}</li><li>${age}</li></ul>";
数据:data=[{"name": "小明","age": "6"}];
结果:<ul><li>小明</li><li>6</li></ul>
写一个函数,讲t中的数据转化成结果
如果data中有多条数据,怎么实现渲染?

大话西游666
浏览 1427回答 2
2回答

ibeautiful

var tpl = '<li>${name}</li><li>${age}</li>';var reg = /\${([A-Za-z0-9_]+)}/g;var data = [{"name": "小明","age": "6"},{"name": "小明明","age": "66"}];var ret= ['<ul>'];for(var i = 0,len = data.length;i < len;++i){&nbsp; &nbsp; ret.push(tpl.replace(reg,function(){&nbsp; &nbsp; &nbsp; &nbsp; return data[i][arguments[1]];&nbsp; &nbsp; }));}ret.push('</ul>');ret = ret.join('');console.log(ret);

跃然一笑

这个主要考你正则了吧t&nbsp;=&nbsp;t.replace(/\$\{([a-z]+)\}/g,function(){&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;data[0][arguments[1]] })
打开App,查看更多内容
随时随地看视频慕课网APP