Javascript中Array.prototype.map()详解(2)

也许你会有疑问,为什么不是[1,2,3]呢?我们知道parseInt方法可接收两个参数,第一个参数为需要转换的值,第二个参数为进制数,不了解的可以戳这里。当我们使用map方法的时候,callback函数接收三个参数,而parseInt最多只能接收两个参数,以至于第三个参数被直接舍弃,与此同时,parseInt把传过来的索引值当成进制数来使用.从而返回了NaN。看下面的输出结果:

复制代码 代码如下:


//Ouputs: 1
console.log(parseInt("1", 0));
//Ouputs: 1
console.log(parseInt("1", undefined));
//Ouputs: NaN
console.log(parseInt("2", 1));
//Ouputs: NaN
console.log(parseInt("3", 2));

后面两个很容易理解,但是前两个为什么返回1呢?为了解释这个问题,我们看看官方的描述:
If radix is undefined or 0 (or absent), JavaScript assumes the following:
a) If the input string begins with “0x” or “0X”, radix is 16 (hexadecimal) and the remainder of the string is parsed.
b) If the input string begins with “0″, radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
c) If the input string begins with any other value, the radix is 10 (decimal).
在第三点中当string为其他值时,进制默认为10。

那么我们如何修改才能使上例正常输出呢?看下例:

复制代码 代码如下:


var result = ["1", "2", "3"].map(function(val) {
    return parseInt(val, 10);
});
//Outputs: [1, 2, 3]
console.log(result);

3.map方法的兼容性:
map方法在IE8及以下浏览器不支持,要想兼容老版本的浏览器,可以:

a) Don't use map.b) Use something like es5-shim to make older IE's support map.c) Use the _.map method in Underscore or Lodash for an equivalent utility function.

以上就是对map方法的理解,希望对初学者有所帮助,文中不妥之处,还望斧正!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgsgsg.html