kaulusp
kaulusp

Reputation: 391

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 */

Upvotes: 1

Views: 259

Answers (2)

Pointy
Pointy

Reputation: 414086

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.

Upvotes: 2

davin
davin

Reputation: 45575

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.

Upvotes: 4

Related Questions