不使用箭头函数时,parseInt 给出 NaN

发布于 2025-01-12 20:25:07 字数 890 浏览 2 评论 0原文

当我没有将其放入箭头函数时,为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沉睡月亮 2025-01-19 20:25:07

map 使用多个参数 (元素、索引、数组) 进行调用,并且 parseInt 需要多个参数(string, radix),因此index作为radix传递。这可能不是你想要的。

NaN 的出现是因为基数必须在 2 到 36 之间。所以你会得到一些奇怪的结果基数是 1,其他索引将尝试根据不断递增的基数进行解析。更奇怪的是,基数 0 意味着使用基数 10(除非字符串以 0x0X 开头,在这种情况下,它意味着使用基数 16 忽略中的前缀预期的方式)。解析失败时,parseInt 返回NaN

The callback to map is called with multiple parameters (element, index, array), and parseInt takes multiple parameters (string, radix) so the index is being passed as the radix. 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 or 0X, in which case it means to use base 16 ignoring the prefix in the expected way). parseInt returns NaN when parsing fails.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文