我在coffeescript 中的while 循环有点麻烦。
原始功能如下,来源是这个答案:
// Return all pattern matches with captured groups
RegExp.prototype.execAll = function(string) {
var match = null;
var matches = new Array();
while (match = this.exec(string)) {
var matchArray = [];
for (i in match) {
if (parseInt(i) == i) {
matchArray.push(match[i]);
}
}
matches.push(matchArray);
}
return matches;
}
它按预期工作。我已经通过js2coffee转换了它,咖啡脚本是:
# Return all pattern matches with captured groups
RegExp::execAll = (string) ->
matches = new Array()
match = null
while match = @exec(string)
matchArray = new Array()
for i of match
matchArray.push match[i] if parseInt(i) is i
matches.push matchArray
matches
编译为:
RegExp.prototype.execAll = function(string) {
var i, match, matchArray, matches;
matches = new Array();
match = null;
while (match = this.exec(string)) {
matchArray = new Array();
for (i in match) {
if (parseInt(i) === i) {
matchArray.push(match[i]);
}
}
matches.push(matchArray);
}
return matches;
};
结果是:
[
[],
[],
[],
[],
[],
[],
[],
[],
[]
]
我认为这不起作用,因为变量范围,因为我能看到的唯一区别是这一行:
RegExp.prototype.execAll = function(string) {
var i, match, matchArray, matches;
与原版相比:
RegExp.prototype.execAll = function(string) {
var match = null;
var matches = new Array();
while (match = this.exec(string)) {
var matchArray = [];
请注意如何matchArray
确定范围...我找不到解决方法,但是当我研究时我发现这些问题是 CoffeeScript 中遗漏了 `do...while` 循环...?以及如何在咖啡脚本的特定范围内声明变量?而且我在这里几乎没有想法......除了这个while循环之外,还有任何其他方式将所有与正则表达式匹配(顺便说一句,我已经尝试过\gm
标志并且它仍然只匹配一个匹配)?或者有没有办法在咖啡脚本中获得这个范围?
整个咖啡脚本代码是:
fs = require 'fs'
text = fs.readFileSync('test.md','utf8')
#console.log text
regex = /^(?:@@)(\w+):(.*.)/gm
# Return all pattern matches with captured groups
RegExp::execAll = (string) ->
matches = new Array()
match = null
while match = @exec(string)
matchArray = new Array()
for i of match
matchArray.push match[i] if parseInt(i) is i
matches.push matchArray
matches
res = regex.execAll text
#console.log regex.exec text
console.log (JSON.stringify(res, null, " ") )
有效的Javascript是这样的:
var fs, regex, res, text;
fs = require('fs');
text = fs.readFileSync('test.md', 'utf8');
regex = /^(?:@@)(\w+):(.*.)/gm;
// Return all pattern matches with captured groups
RegExp.prototype.execAll = function(string) {
var match = null;
var matches = new Array();
while (match = this.exec(string)) {
var matchArray = [];
for (i in match) {
if (parseInt(i) == i) {
matchArray.push(match[i]);
}
}
matches.push(matchArray);
}
return matches;
}
res = regex.execAll(text);
//console.log(regex.exec(text));
console.log(JSON.stringify(res, null, " "));