小编Mis*_*ybe的帖子

为什么不在关闭中重置变量(Javascript)

我一直在努力学习关闭,但有一件事仍困扰着我.如果我有以下代码:

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
add();

// Returns "3"
Run Code Online (Sandbox Code Playgroud)

如果我调用add()三次,为什么不每次都将counter设置为零,然后返回一个递增计数器的匿名函数?一旦自动调用函数运行,它是否会跳过它?对不起,如果问题看起来很简单,我很难理解它.任何帮助将不胜感激.

javascript closures scope self-invoking-function

2
推荐指数
1
解决办法
528
查看次数

无效的正则表达式:无重复错误

I am trying to make an app that counts how many times each character occurs in a given string. So for example, in the string "hello 12355" it should match with all the numbers past 1, and not with the "hello" part. However, when I try to run the code, I get this in the console:

"Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat at new RegExp ()"

When I change xy to anything past 92, however, the code …

javascript regex unicode counter

1
推荐指数
1
解决办法
1万
查看次数

字符计数器不会打印所有字符

我正在制作一个角色计数器作为爱好代码.到目前为止,它正在运作,但我有一个小故障我似乎无法解决.当我写下" a,b,c"时,它会正确写入a:1 b:1 c:1.但是当我写" a,a,c,c"时,它只会写a:2.我不确定是什么问题.这是我的代码的JavaScript部分(myFunction由按钮激活,testinput.value是我正在使用的文本框的值):

function myFunction() {
  var occurence = document.getElementById("testinput").value;
  var cycleOne = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
    "u", "v", "w", "x", "y", "z"
  ];
  for (i = 0; i < 26; i++) {
    var counter = new RegExp(cycleOne[i], 'g');
    document.write(occurence.match(counter).length);
  }
}
Run Code Online (Sandbox Code Playgroud)

javascript regex string

0
推荐指数
1
解决办法
53
查看次数