Executing function for every key in array w/o loop
I'm looking for the best practice for executing encodeURIComponent
(or some other function) for every key in array, before joining it to one string.
This could be done with a loop like this:
var dynamicArray = ['uri1', 'uri2', 'hax&%hax'];
var max = dynamicArray.length,
i,
url = '';
for (i=0;i<max;(i++))
{
url += '/' + encodeURIComponent(dynamicArray[i]);
}
alert(url);
/* RESULT: /uri1/uri2/hax%26%25hax开发者_开发知识库 */
But I'm looking for something like this (without a loop):
encodeURIComponent(dynamicArray).join('/'); /* This won't work */
encodeURIComponent(dynamicArray.join('/')); /* Can't do this, wrong result */
dynamicArray.map(encodeURIComponent).join('/');
Check out MDC for an implementation of map
for non-compatible platforms.
Of course, internally there is a loop in map
's implementation.
Well in some modern browsers there's a ".map()" method for arrays:
var encoded = dynamicArray.map(function(str) {
return encodeURIComponent(str);
});
or without your own function wrapper, which in this case isn't really necessary:
var encoded = dynamicArray.map(encodeURIComponent);
The idea is that ".map()" is called for each element of the array. The function it's passed should return some result, and those results are gathered up into a new array, which is ultimately the returned value. You can then ".join()" that, or do whatever else you need.
The Mozilla documentation for ".map()" has a "polyfill" block of code you can use to provide ".map()" in browsers that don't natively support it. Note also that many utility libraries have their own ".map()", and some of those have slightly different semantics. For example, the jQuery ".map()" has (to me, unpleasant) semantics for returned values from the callback function.
精彩评论