我创建这个函数是为了替换字符串中的值并调用名称为该值的函数。
$(function() {
var str = "Homer drank {{countBeers}} beers";
function countBeers() {
console.log(this);
return 10 + 10;
}
function convert(str) {
console.log(this);
str = "'" + str.replace(/{{(.*?)}}/g, "' + $1.call(this) + '") + "'";
OR
str = "'" + str.replace(/{{(.*?)}}/g, "' + $1(this) + '") + "'";
return eval(str);
}
var output = convert.call(this, str);
$('body').append(output); //Homer drank 20 beers
});
这似乎工作正常,但我不会使用 eval。 还可以用其他方法吗?
谢谢
最佳答案
您可以将对象与该函数一起使用。
function convert(str) {
return str.replace(/{{(.*?)}}/g, function (_, f) {
return op[f] ? op[f]() : f;
});
}
var str = "Homer drank {{countBeers}} beers",
op = { countBeers: function () { return 10 + 10; } };
console.log(convert(str));
关于javascript - Jquery替换字符串中的值并使用名称为值的args调用函数而不使用eval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37341676/