Looking for javascript techniques [closed]
I'm trying to learn some fresh and hacky javascript techniques and on my quest to do so, here is a function I mocked up:
function doAction(index) {
for(var a = Array.prototype.slice.call(arguments, 1),
i = 0, r = [], l = a.length; i < l; i++)
r.push(a[i][index]);
return r;
}
doAction(2, ['a','b','c'],['a','b','c'],['a','b','c']) //==> ["c", "c", "c"]
This is basically what it does: get every nth element from a number of arrays and return them in a new one.
I would like to improve this function with freaky ninja-style ideas, not necessarily shorten the code, but rather optimize it. (You most probably already noticed the infamous Array.prototype.slice
thingy);
As English is not my native tongue, I would also like a decent name for the action performed by this function. Thanks in advance 开发者_如何学运维guys (and women!)
Oh, here's a Fiddle: http://jsfiddle.net/Exv7Z/
EDIT: Talking about optimizing things... (Idea from the genius in the comments)
function doAction(index) {
return Array.prototype.slice.call(arguments, 1).map(function(b) {
return b[index];
});
}
There is not much to optimize I think, but i'll do two change
- First, declaring a real argument instead of using some that aren't here
- Second, I'd put the variable initialisation outside of the for.
Those two points aren't really optimization, but it's rather a matter of readability (and of taste maybe)
The code would be something like
function doAction(index,a) {
var r = [], l = a.length;
for(var i=0; i < l; i++) r.push(a[i][index]);
return r;
}
and the call would be doAction(2, [['a','b','c'],['a','b','c'],['a','b','c']]);
It can be simplified like this as there is no need to copy the arguments array. It only needs to be copied of it needs to be modified:
function doAction(index) {
var r = [];
for(var i = 1; i < arguments.length; i++) r.push(arguments[i][index]);
return r;
}
or if you want to keep the len variable, it can be this:
function doAction(index) {
var r = [];
for(var i = 1, len = arguments.length; i < len; i++) r.push(arguments[i][index]);
return r;
}
jsFiddle here: http://jsfiddle.net/jfriend00/Z22w7/.
As for a name, you might call it multiSlice()
or multiIndex()
.
精彩评论