我如何在 JavaScript 中定义一个正则表达式组并在一行中访问它?
我尝试使用 eval 来获取定义的正则表达式组的值:
let str = `
global stuff = 1;
global h = 0;
function inc(arg) {
inc = inc + 1;
};
main {
repeat(inc, 10);
}
`;
str = str.replace(/repeat\((.*?|$1), (.*?|$2)\)/gm, "$1".repeat(eval("$2")));
console.log(str);
我希望输出是
`global h = 0;
function inc(arg) {
h = h + 1;
};
main {
inc;
inc;
inc;
inc;
inc;
inc;
inc;
inc;
inc;
inc;
}`
,因为我想将 repeat(inc, 10);
转换为
inc;
inc;
inc;
...
,但它给了我这个错误:ReferenceError: $2 is not defined
。我知道我在这里做的事情可能看起来很晦涩,但它是我为我正在制作的编程语言制作的编译器代码的一部分。
最佳答案
replace 方法可以接受一个函数。这段代码在一行中完成了您的要求。
let str = `
global stuff = 1;
global h = 0;
function inc(arg) {
inc = inc + 1;
};
main {
repeat(inc, 10);
}
`;
str = str.replace(/(\s+)repeat\((.*?|$1), (.*?|$2)\);/gm, (match, p0, p1, p2) => (p0 + p1 + ";").repeat(p2));
console.log(str);
关于javascript - 如何获取组的值并在 JavaScript 的一行中定义它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199401/