开发者

JavaScript 1.6 Array.map() and Array.filter() not working with built in functions as arguments

开发者 https://www.devze.com 2022-12-27 05:23 出处:网络
This works fine: [\"655971\", \"2343\", \"343\"].map(function(x) { return parseInt(x) }) // [655971, 2343, 343]开发者_运维问答

This works fine:

["655971", "2343", "343"].map(function(x) { return parseInt(x) }) // [655971, 2343, 343]开发者_运维问答

But this doesnt:

["655971", "2343", "343"].map(parseInt) // [655971, NaN, NaN]

The same happens for Array.filter()

What am I missing here?


It's because map passes more arguments than just the array item into the callback function. You get:

callback(item, index, array)

Normally your function would just ignore the arguments it didn't need. But parseInt accepts an optional second parameter:

parseInt(string, base)

for the first call, base is the index 0. That works okay because ECMAScript defines that base=0 is the same as omitting the argument, and consequently allows decimal, octal or hex (using decimal in this case).

For the second and third items, base is 1 or 2. It tries to parse the number as base-1 (which doesn't exist) or base-2 (binary). Since the first number in the string is a digit that doesn't exist in those bases, you get a NaN.

In general, parseInt without a base is pretty questionable anyway, so you probably want:

["655971", "2343", "343"].map(function(x) { return parseInt(x, 10) })


The problem is that map expects that the callback should be a function that accepts three arguments, callbackfn(value, index, array).

The second argument is clashing with the radix argument of the parseInt(string, radix) function.

Map calls parseInt like this for each element:

parseInt("655971",0); // 655971
parseInt("2343", 1);  // NaN
parseInt("343", 2);   // NaN

The first one works because if radix is undefined or 0, it is assumed to be 10.


Array.Filter takes a function that returns information whether or not the item to evaluated satisfies the condition. IsNumeric will work for what you want.

http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号