如何解决这种家庭作业逻辑?

时间:2018-07-27 10:10:11

标签: javascript jquery

这是我的挑战:

  

编写一个函数,该函数接受字符串输入并返回一个函数。返回的函数应该一次并循环打印字符串的字符。

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 < arr.length; i++) {
    if (i === 3) {
      continue;
    }
    text = arr[i];
  }
  document.getElementById("demo").innerHTML = text;
}
<p id="demo"></p>

2 个答案:

答案 0 :(得分:5)

这个问题从来没有问过生成器,但是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

答案 1 :(得分:-1)

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  var s = "overpopulation";
  for (var i = 0; i < s.length; i++) {
    document.write(s.charAt(i) + '<br/>');
  }
</script>