作者:pS看云梦山水Tn | 来源:互联网 | 2022-12-09 13:54
这是我的挑战:
编写一个函数,它接受一个字符串输入并返回一个函数.返回的函数应该一次打印一个字符串的字符并循环.
var xyz = MyFunction('xyz');
xyz(); // should return 'x' on this first call
xyz(); // should return 'y' on this second call
xyz(); // should return 'z' on this third call
xyz(); // should return 'x' again on this fourth call
window.Onload= function() {
var xyz = 'xzy';
myFunction(xyz);
}
function myFunction(xyz) {
var text = xyz;
var arr = text.split('');
var i;
for (i = 0; i
1> Keith..:
问题永远不会要求生成器,但Javascript很容易创建一个返回函数的函数,添加到此可以使用闭包来捕获状态.
例如.
function MyFunction (input) {
var char_pos = 0;
return function () {
return input[char_pos++ % input.length];
}
}
var xyz = MyFunction('xyz');
console.log(xyz()); // should return 'x' on this first call
console.log(xyz()); // should return 'y' on this second call
console.log(xyz()); // should return 'z' on this third call
console.log(xyz()); // should return 'x' again on this fourth call