又重新阅读了一遍andrew的原文,在原文下面的评论中,赫然发现也有人早提出参数个数的问题,同样懒惰的楼猪直接拷贝原文评论答复了一下,同时还发现说漏了很重要的一个注意点array.prototype.slice。
下面统一补充说明一下:
1、string.format的参数个数
在andrew的原文中,已经有人指出:
eric d. hi, thanks for that brilliant article. made a lot of things a lot clearer!
note: new regexp(%([1- + arguments.length + ]), g); will fail passed 9 arguments (the regexp would be %([1-10]) so it will only match %0 and %1).
i think an easy fix would be something like:
function format(string) { var args = arguments; var pattern = new regexp(%([0-9]+), g); return string(string).replace(pattern, function(match, index) { if (index == 0 || index >= args.length) throw invalid index in format string; return args[index]; }); };
(sorry for nitpicking, i understand it was only an example and brevety is the main objective, but its a great function to have)
posted on: january 20th 2009, 12:01 am
这个留言的家伙给足了作者面子,称“i understand it was only an example and brevety is the main objective, but its a great function to have”。原来,原文中定义的正则表达式能够验证的数字范围是...原来如此啊,哈哈,楼猪心虚的笑了。
2、array.prototype.slice
将arguments转换成array的方法是通过array.prototype.slice.call(arguments);方式转换的,也就是说类数组方式的对象都可以通过slice的方式实现到array的转换,说到类数组对象的转换,真的很有必要重新记录总结一下array的原型方法slice。
(1)、常见用法
楼猪在早前的这篇里通过一段代码一带而过介绍过slice方法:slice(start,end):返回数组对象的一个子集,索引从start开始(包括 start),到end结束(不包括end),原有数组不受影响。其实我们可以大胆猜测slice函数内部应该是定义了一个数组变量,然后通过循环,将数组对应索引值push进变量,最后return这个array变量。
(2)、“不是array,我们也想要变成array”
不是array,但是有length属性,可以根据索引取值,比如本文中的arguments,我们可以通过下面的方式转换为真实数组:
复制代码 代码如下:
function test() {
var args = array.prototype.slice.call(arguments);
alert(args.length);
args.push(jeff); //push
args.push(wong);
alert(args.length); //2
alert(args.pop()); //pop
alert(args.length); //1
}
test();
我们看到push和pop方法都起作用了。同样,nodelist也有类似特性。怎么样将nodelist转换成array?看过楼猪原文的读者可能会觉得这都是陈词滥调,还是多说一句,在ie下,array.prototype.slice.call(nodelist)就不是那么回事了,最后再贴一次将nodelist转换为array并且兼容ie和其他浏览器的方法结束本文:
复制代码 代码如下:
var nodelist =something;//一个nodelist变量
var arr = null; //数组
try { //ie
arr = new array();
for (var i = 0; i arr.push(nodelist[i]);
}
} catch (e) {//其他浏览器
arr = array.prototype.slice.call(nodelist);
}
作者:jeff wong
