1

javascript 面试题:["1", "2", "3", "4"]....

 2 years ago
source link: https://foofish.net/JavaScript-interview-array-map-parseint.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

直接看题,下面输出结果是多少

const nums = ["1", "2", "3", "4"]
console.log(nums.map(parseInt))

parseInt函数可以将字符串数字转换成整数类型,咋一看你以为结果是:

[1, 2, 3, 4]

然而,实际结果却超乎你想象

[ 1, NaN, NaN, NaN ]

为什么会出现这种情况? 还是从官方文档去找问题的根源

map 定义

map方法创建一个新数组,其结果是该数组中的每个元素调用一次提供的函数后的返回值。

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
})

map 接收的 callback函数默认接收3个参数。

  1. currentValue 是每次迭代数组中的当前元素
  2. index是对应元素索引位置
  3. array 是原数组

除了 currentValue 是必选参数,另外两个参数可选。而parseInt(string, radix)是解析一个字符串并返回指定基数的十进制整数的函数, radix 是2-36之间的整数。

如果 radix 是 undefined、0或未指定的,JavaScript会假定以下情况:

  1. 如果输入的 string以 "0x"或 "0x"(一个0,后面是小写或大写的X)开头,那么radix被假定为16,字符串的其余部分被当做十六进制数去解析。
  2. 如果输入的 string以 "0"(0)开头, radix被假定为8(八进制)或10(十进制)。具体选择哪一个radix取决于实现。ECMAScript 5 澄清了应该使用 10 (十进制),但不是所有的浏览器都支持。因此,在使用 parseInt 时,一定要指定一个 radix
  3. 如果输入的 string 以任何其他值开头, radix 是 10 (十进制)。

如果字符串中的数字不在基数范围内,就会返回NaN,比如 radix 2,那么字符串的可选数字只有0和1,radix 为8,字符串数字只能是0-7。以此类推。

所以,回到前面那道题,迭代第一个元素时,相当于

// 第0个元素
parseInt("1", 0)  // 1
//第1个元素
parseInt("2", 1)  // NaN
//第2个元素
parseInt("3", 2)  // NAN
//第3个元素
parseInt("4", 3)  //NAN

要得到预期的结果,我们可以自定义函数,明确只接收一个参数

const nums = ["1", "2", "3", "4"]
console.log(nums.map(str=>parseInt(str, 10)))
  1. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/parseInt
  2. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK