I re-read Andrew's original article again. In the comments below the original article, I was surprised to find that someone had already raised the issue of the number of parameters. Lou Zhu, who was also lazy, directly copied the original article and replied. He also found that he had missed something very important. One point to note Array.prototype.slice.
The following is a unified explanation:
1. The number of parameters of string.format
In Andrew’s original text, someone has already pointed out:
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
The guy who left the message gave the author enough face, saying "I understand it was only an example and brevety is the main objective, but its a great function to have". It turns out that the range of numbers that can be verified by the regular expression defined in the original article is... So that's it, haha, Lou Zhu smiled guiltily.
2. Array.prototype.slice
The method of converting arguments into Array is through Array.prototype.slice.call(arguments);, that is to say, the class Array objects can be converted to Array through slice. When it comes to the conversion of array-like objects, it is really necessary to re-record and summarize Array's prototype method slice.
(1), common usage
Lou Zhu introduced the slice method through a piece of code in an earlier article: slice(start, end): returns a subset of the array object, the index starts from start Start (including start) and end at end (excluding end). The original array will not be affected. In fact, we can boldly guess that an array variable should be defined inside the slice function, and then through a loop, the corresponding index value of the array is pushed into the variable, and finally the Array variable is returned.
(2), "It's not an Array, we also want to become an Array"
It's not an Array, but it has a length attribute, which can be valued based on the index. For example, the arguments in this article can be converted to Real array: