我试图创建一种在Javascript中实现循环的新方法。用户会输入
环路(N) { //重复的代码 }
并且新的循环函数将重复大括号'n'次内的代码。它只需在后端使用计数器变量实现while循环。
我知道如何创建原型函数,但我需要的不仅仅是将参数传递给函数。我希望loop(n)语句重复编码器指定的代码块。
我已经看过Sweet.js了,但似乎没有提到做我提议的事情。
我该怎么做呢?
Sweet.js文档确实有an example你可以申请循环。这是一个简单的版本:
syntax loop = function (ctx) {
const count = ctx.next().value;
const code = ctx.next().value;
return #`for (let __n = 0; __n < ${count}; ++__n) ${code}`;
}
...虽然可能有更好的方法来创建循环变量。
你会这样使用:
loop 10 {
// ...your code here...
}
我可能想要指定用于计数器的标识符:
syntax loop = function (ctx) {
const count = ctx.next().value;
const identifier = ctx.next().value;
const code = ctx.next().value;
return #`for (let ${identifier} = 0; ${identifier} < ${count}; ++${identifier}) ${code}`;
}
然后:
loop 10 index {
console.log(index);
}
我希望有一种方法可以让标识符成为可选项。
也就是说,我只使用你传递回调函数:
function loop(end, callback) {
for (let n = 0; n < end; ++n) {
callback(n);
}
}
loop(10, n => console.log(n));
.as-console-wrapper {
max-height: 100% !important;
}
您可以非常轻松地完成更多功能:
function loop(end, start, step, callback) {
if (typeof end !== "number") {
throw new Error("'end' should be a number");
}
if (typeof start === "function") {
callback = start;
start = 0;
step = 1;
} else if (typeof step === "function") {
callback = step;
step = 1;
}
if (typeof start !== "number") {
throw new Error("'start' should be a number");
}
if (typeof step !== "number") {
throw new Error("'step' should be a number");
}
for (let n = start; n < end; n += step) {
callback(n);
}
}
console.log("loop(3, n => console.log(n));");
loop(3, n => console.log(n));
console.log("loop(3, 1, n => console.log(n));");
loop(3, 1, n => console.log(n));
console.log("loop(6, 0, 2, n => console.log(n));");
loop(6, 0, 2, n => console.log(n));
.as-console-wrapper {
max-height: 100% !important;
}