String.formatString=function(format){
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/\{(\d+)\}/g, function(m1, i){
alert(m1 +"\n" +i);
return args[i];
});
};
var cls = 'my-class', text = 'Some text',value='kkkk';
var s = String.formatString('<div class="{0}">{1}{2}</div>', cls, text,value);
alert(s);请问function(m1, i){
alert(m1 +"\n" +i);
return args[i];
} 这个里面的参数如何理解? 他们继承哪个参数呢?为什么i的变量可以自动设置值呢?象for循环里面的i变量?
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/\{(\d+)\}/g, function(m1, i){
alert(m1 +"\n" +i);
return args[i];
});
};
var cls = 'my-class', text = 'Some text',value='kkkk';
var s = String.formatString('<div class="{0}">{1}{2}</div>', cls, text,value);
alert(s);请问function(m1, i){
alert(m1 +"\n" +i);
return args[i];
} 这个里面的参数如何理解? 他们继承哪个参数呢?为什么i的变量可以自动设置值呢?象for循环里面的i变量?
alert(m1 +"\n" +i);
return args[i];
} 那么我 var y = t("sss", 0);
alert(y)
此时 y = "sss";
return format.replace(/\{(\d+)\}/g, function(m1, i){
alert(m1 +"\n" +i);
return args[i];
}); 在这段代码中,m1,i 的实参是哪个,如何给function(m1,i)传的?
obj.replace(/xxxx/ig,function(){
//xxxxx
});其执行过程为每次匹配到一个字符串则执行一次第二个参数的function函数。
其中 function的参数是这样的:
arguments[0], 匹配的串源
arguments[1] ... arguments[arguments.length -3],匹配()内容,相当于常用的 $1, $2...
arguments[arguments.length -2],匹配串的位置偏移 offset
arguments[arguments.length -1],整个字符串源可以用以下脚本去测试:
var j=1;
var str="document.write('xxxxxxx');document.write('aaaa')";
str.replace(/document.write\((.*?)\)/ig,function(){
alert("找到第"+(j++)+"个匹配字符串");
for(var i=0;i<arguments.length;i++){
alert("arguments["+i+"]="+arguments[i]);
}
});<script type="text/javascript">
var j=1;
var str="document.write('xxxxxxx');document.write('aaaa')";
str.replace(/document.write\((.*?)\)/ig,function(){
alert("找到第"+(j++)+"个匹配字符串");
for(var i=0;i<arguments.length;i++){
alert("arguments["+i+"]="+arguments[i]);
}
});
</script>