Array.from TypeError: 0 is not a function

I get a strange error while trying to pass Array.from to Array.prototype.map .

 let fn = Array.from.bind(Array); // [Function: bound from] fn('test') // [ 't', 'e', 's', 't' ] ['test'].map(s => fn(s)) // [ [ 't', 'e', 's', 't' ] ] ['test'].map(fn) // TypeError: 0 is not a function 

Full error:

 TypeError: 0 is not a function at Function.from (native) at Array.map (native) at repl:1:10 at REPLServer.defaultEval (repl.js:260:27) at bound (domain.js:287:14) at REPLServer.runBound [as eval] (domain.js:300:12) at REPLServer.<anonymous> (repl.js:429:12) at emitOne (events.js:95:20) at REPLServer.emit (events.js:182:7) at REPLServer.Interface._onLine (readline.js:211:10) 

What's happening?

+7
javascript arrays
source share
1 answer

map calls its callback with three arguments: a record, an index, and a repeating object. Array.from expects that if it is assigned a second argument, it is a matching function and therefore tries to call it on each "element", it builds an array of. Index 0 on the first call is not a function, so Array.from fails.

Put it another way, equivalent

 ['test'].map(fn) 

not

 ['test'].map(e => fn(e)) 

but rather

 ['test'].map((e, i, a) => fn(e, i, a)) 

... where e is the record, i is its index, and a is the "array" traversed by map . Since i not a function, Array.from fails.

You get the same with a few other array functions like forEach , some , ...


If you do this a lot, you may find it useful to use a function that you can use to filter everything except the first argument:

 function passOneArg(f) { return function(a) { return f.call(this, a); }; } 

which you can use as follows:

 ['test'].map(passOneArg(fn)) 

Or maybe even

 function limitArgs(f, count) { return function() { return f.apply(this, Array.prototype.slice.call(arguments, 0, count)); }; } 

then

 ['test'].map(limitArgs(fn, 1)) 

These, of course, are the two worst function names on the planet, but you get the idea ... :-)

+9
source share

All Articles