最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Apr 15, 2010 at 18:01 bucabaybucabay 5,2952 gold badges27 silver badges37 bronze badges 1
  • In case anyone is interested, this situation is described, in detail, on the the MDN Array.prototype.map page which is referenced by the following blog post:Allen Wirfs-Brock - A JavaScript Optional Argument Hazard. – Mr. Polywhirl Commented Feb 18, 2015 at 14:13
Add a comment  | 

3 Answers 3

Reset to default 22

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)

  1. 暂无评论