JavaScript 如何从字符串创建函数
任务是根据给定格式的字符串创建函数。下面列出了几种方法:
- 使用Function()构造函数
- 使用eval()方法
方法1:使用Function()构造函数
- 使用 Function()构造函数 从字符串创建函数。
- 它接受任意数量的参数(以字符串形式)。最后一个参数应该是函数的主体。
- 在这个示例中,只传递了函数的主体,并返回一个值。
示例1: 该示例实现了上述方法。
let func = 'return "This is return value";';
// We can use 'func' as function
function funFromString() {
let func2 = Function(func);
// Now 'func' can be used as function
console.log(func2());
}
funFromString();
输出
This is return value
方法2:使用eval()方法
- 使用 eval()方法 从字符串中创建一个函数。
- 它接受字符串形式的函数,并将其转换为JavaScript函数。
- 在此示例中,它接受两个参数并返回这两个数字的和。
示例2: 此示例使用上述讨论的方法。
const str = "var func = function (a, b) { return a + b; };";
// Till this point we can use 'func' as function
function funFromString() {
// Converting the string to function
eval(str);
console.log(func(2, 5));
}
funFromString();
输出
7
极客教程