不使用箭头函数时,parseInt 给出 NaN
当我没有将其放入箭头函数时,为什么 parseInt
给出 NaN
?奇怪的是,只有 50
得到了正确的解析,而其他的则没有......将 parseInt
本身作为参数有什么问题吗?我想确保它们都是整数,它与箭头函数一起使用,但我想知道为什么它不能仅传递整个函数。即使尝试使用 .map(parseInt.bind(window))
将其绑定到 window
也不起作用。是源代码的问题吗?
function toPercent(array) {
let arr = array.map((a, _, s) => a / s.reduce((a, b) => a+b) * 100)
console.log(arr)
return arr.map(parseInt)
}
console.log(toPercent([2, 1, 1]))
function toPercent(array) {
let arr = array.map((a, _, s) => a / s.reduce((a, b) => a+b) * 100)
console.log(arr)
return arr.map(n => parseInt(n))
}
console.log(toPercent([2, 1, 1]))
Why does parseInt
give NaN
when I am not putting it in an arrow function? What's strange is that only 50
is getting properly parsed, while the others are not... Is there something wrong with putting parseInt
itself as an argument? I want to make sure all of them are whole numbers, it works with an arrow function but I would like to know why it doesn't work just passing in the whole function. Even trying to bind it to window
with .map(parseInt.bind(window))
doesn't work. Is it a problem with the source code?
function toPercent(array) {
let arr = array.map((a, _, s) => a / s.reduce((a, b) => a+b) * 100)
console.log(arr)
return arr.map(parseInt)
}
console.log(toPercent([2, 1, 1]))
function toPercent(array) {
let arr = array.map((a, _, s) => a / s.reduce((a, b) => a+b) * 100)
console.log(arr)
return arr.map(n => parseInt(n))
}
console.log(toPercent([2, 1, 1]))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对
map
使用多个参数(元素、索引、数组)
进行调用,并且parseInt
需要多个参数(string, radix)
,因此index
作为radix
传递。这可能不是你想要的。NaN 的出现是因为基数必须在 2 到 36 之间。所以你会得到一些奇怪的结果基数是 1,其他索引将尝试根据不断递增的基数进行解析。更奇怪的是,基数 0 意味着使用基数 10(除非字符串以
0x
或0X
开头,在这种情况下,它意味着使用基数 16 忽略中的前缀预期的方式)。解析失败时,parseInt
返回NaN
。The callback to
map
is called with multiple parameters(element, index, array)
, andparseInt
takes multiple parameters(string, radix)
so theindex
is being passed as theradix
. That's probably not what you intended.The NaNs arise because the radix must be between 2 and 36. So you'll get some strange results radix is 1 and other indices will attempt to parse according to the ever-incrementing radix. By even further quirkiness, radix 0 means to use base 10 (unless the string starts with
0x
or0X
, in which case it means to use base 16 ignoring the prefix in the expected way).parseInt
returnsNaN
when parsing fails.