给出以下代码:
String.method('deentityify', function () {
var entity = {
quot: '"',
lt: '<',
gt: '>'
};
return function () {
return this.replace(/&([^&;]);/g,
function (a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
);
};
}());
document.write('deentityify: ' + '<">'.deentityify() + '<br>');
关于
function (a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
匿名函数如何获取参数值a、b?当然我已经尝试过,输出是正确的。谁能帮我吗?
最佳答案
该函数实际上是“replace”调用的参数。正则表达式匹配作为参数传递到函数中。 以另一种方式编写代码,它看起来是:
function match(a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
var result = this.replace(/&([^&;]);/g, match)
参数的名称(a 和 b)无关紧要,可以是您喜欢的任何名称。 第一个参数将是匹配的值,后续参数将是匹配组的值。因此,为了清楚起见,该函数可以写为:
function matchFn(match, group1, group2, group3) {
var r = entity[group1];
return typeof r === 'string' ? r : match;
}
引用MDN
A function to be invoked to create the new substring (to put in place of the substring received from parameter #1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.
关于javascript - 关闭的 javascript 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14728503/