Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How to convert javascript array to function

I have an array of arbitrary values. I Wrote a function that transforms the array to an array of functions that return the original values, so instead of calling a[3], I will call a3.

Here is my code which does not work? code. It gives this error Cannot call method '1' of undefined.

var numToFun = [1, 2, { foo: "bar" }];
var numToFunLength = numToFun.length;
function transform(numTo) {
 for (var i = 0; i < numToFunLength; i++) {
 (function(num){
 numTo.unshift(function() {
 return num;
 });
 }(numTo.pop())) 
 }
}
var b = transform(numToFun);
console.log(numToFun);
console.log(b[1]());​

Answer*

Draft saved
Draft discarded
Cancel
3
  • +1 from me, certainly simpler and cleaner. And even the original array is preserved! Commented Jul 24, 2012 at 9:19
  • Is it efficient way to do this? I mean is it faster tan mine solution? Commented Jul 24, 2012 at 9:22
  • 1
    @al0ne evenings: well, it is certainly faster to read if you ask me. ;) Other than that I can't imagine any use case where the difference in speed of both of those solutions would be even noticeable. I would always recommend starting from the most readable way to write your code and only consider optimising it for speed when you profile it and when it really matters. Now when I'm thinking about it there may be even more elegant solution which I may post in few minutes. Commented Jul 24, 2012 at 9:36

lang-js

AltStyle によって変換されたページ (->オリジナル) /