【发布时间】:2016-10-06 13:29:50
【问题描述】:
大家好,我需要编写一个函数,该函数接受一个字符串和一个对象并将该对象插入到字符串中,就像这样
// interpolate("Its {weather} outside", {weather: 'damn Hot'})
// returns 'It's damn hot outside'
// interpolate( "Hi my name is {name}", {name: 'John'});
// returns 'Hi my name is John'
无论物体走多深都应该如此,这样的情况
// interpolate("Hi my name is {contact.name}", {contact: {name: 'john'}});
我有点卡住了,起初我尝试将字符串拆分为一个数组,然后尝试将对象值放入数组中,然后将其重新组合在一起,但这不适用于所有测试用例,有人可以帮我写这个吗功能并解释他们的解决方案吗?谢谢你
所以我尝试了类似的方法,但并不能真正适用于所有测试用例,这是一个模板文字,但该函数应该只将这些值作为参数单独工作,否则我很卡住。 .
function interpolate(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
var result = [strings[0]];
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
var t1Closure = interpolate`${0}${1}${0}!`;
t1Closure('Y', 'A'); // "YAY!"
var t2Closure = interpolate`${0} ${'foo'}!`;
console.log(t2Closure('Hello', {foo: 'World'})); // "Hello World!"
好的,我越来越近了,所以我将问题分成两个函数并需要将它们组合起来,唯一的问题是我不确定如何让最后一个用例在没有模板文字的情况下工作
var something = "something";
var sub = function(str) {
return str.replace(/#\{(.*?)\}/g,
function(whole, expr) {
return eval(expr)
})
}
console.log(sub("hello #{something}"));
var objectValue = function(str, obj){
for(key in obj) {
if(obj.hasOwnProperty(key)) {
var value = obj[key];
return str + value;
}
}
}
console.log(objectValue("hi my name is ", {contact: {name: 'john'}}));
【问题讨论】:
-
向我们展示您迄今为止编写的有问题的代码。
-
你考虑过使用 ES6 模板字符串吗?
-
很抱歉您没有成功,但没有人会为您编写代码。发布您尝试过的任何内容,说明您失败的地方,社区将很乐意为您提供帮助。
-
你应该看看How can I construct a Template String from a regular string?,可能还有Defer execution for ES6 Template Strings。总之,模板文字并不是最好的工具。请改用模板库。
标签: javascript