JavaScript ["1", "2", "3"].map(parseInt) 答案是多少
问题
JavaScript ["1", "2", "3"].map(parseInt)
答案是多少
参考答案
[1, NaN, NaN]
原理解释
map()
方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
- map参考 : https://www.axihe.com/api/js-es/ob-array/map.html
- parseInt参考 : https://www.axihe.com/api/js-es/ob-attr-fn/parse-int.html
[1, NaN, NaN]
因为 parseInt 需要两个参数 (val, index) 但 map 传了 3 个 (element, index, array)
而 parseInt
需要两个参数中的 index 表示解析时用的基数。
map 传了 3 个 (element, index, array),对应的 index 不合法导致解析失败。
下面的代码可以帮助你理解
let _typeof = function (data) {
let value = /\[object (\w+)\]/.exec(
Object.prototype.toString.call(data)
);
return value ? value[1].toLowerCase() : '';
}
var kvArray = ["1", "2", "3"];
var reformattedArray = kvArray.map(function (arg1, arg2, arg3) {
console.log(`
arg1:${arg1}, ${_typeof(arg1)}
arg2:${arg2}, ${_typeof(arg2)}
arg3:${arg3}, ${_typeof(arg3)}
`)
return parseInt(arg1, arg2, arg3)
});
console.log('---', reformattedArray)
更多面试题
如果你想了解更多的前端面试题,可以查看本站的WEB前端面试题 ,这里基本包涵了市场上的所有前端方面的面试题,也有一些大公司的面试图,可以让你面试更加顺利。
面试题 | ||
---|---|---|
HTML | CSS | JavaScript |
jQuery | Vue.js | React |
算法 | HTTP | Babel |
BootStrap | Electron | Gulp |
Node.js | 前端经验相关 | 前端综合 |
Webpack | 微信小程序 | - |
这些题库还在更新中,如果你有不错的面试题库欢迎分享给我,我整理后放上来;人人为我,我为人人,互帮互助,共同提高,祝大家都拿到心仪的Offer!