如何在JS中实现以下逻辑
的例子:
Let y = alertMyPreviousParam(“1”);
Let z= y(‘2’)
// show output as 1
Let a = z(‘3’)
// show output as 2
Let b = a(‘ra’)
// show output as 3
Let c = b(‘z’)
// show output as ‘ra’,
尽管各种Syntax error
1)由‘
和’
包围的字符串不是有效的javascript字符串,与“
和”
类似。使用"
或'
。
2)变量应该用let
而不是Let
来声明。
您可以在这里利用closure
和Higher order function(HOF)
function alertMyPreviousParam(arg) {
let last = arg;
return function (curr) {
console.log(last);
last = curr;
return alertMyPreviousParam(curr);
};
}
let y = alertMyPreviousParam("1");
let z = y("2");
// show output as 1
let a = z("3");
// show output as 2
let b = a("ra");
// show output as 3
let c = b("z");
// show output as ‘ra’,
您将需要查看闭包。下面是一个例子:
let var = null
let next = null
const myFunc = (newnext) => {
var = next
next = newnext
return var
}
抱歉格式不对,我在用手机
函数alertMyPreviousParam,返回一个新函数,并输出之前的输入。这可以通过以下方式实现:
let alertMyPreviousParam = (x) => (y) => {
console.log(x);
return alertMyPreviousParam(y);
}