map + parseInt - 奇怪的结果 [英] map + parseInt - strange results

查看:115
本文介绍了map + parseInt - 奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

console.log("1,2,3".split(",").map(parseInt))

打印

[1, NaN, NaN]

为什么?

此处添加更多不必要的文字这个问题满足SO质量标准,无论这意味着什么。

Adding some more unnecessary text here to make this question "meet SO quality standards", whatever that means.

推荐答案

这里将详细讨论: http://www.wirfs-brock.com/allen/posts/166 。提出这个问题的解决方案,以及显而易见的

This is discussed in much detail here: http://www.wirfs-brock.com/allen/posts/166. Proposed solutions to this problem, along with the obvious

a.map(function(e) { return parseInt(e, 10)})

还包括Number构造函数:

also include the Number constructor:

a.map(Number)

或基于解决方案部分应用程序(请参阅 http://msdn.microsoft.com/en-us/scriptjunkie/ gg575560 更多信息):

or a solution based on partial application (see http://msdn.microsoft.com/en-us/scriptjunkie/gg575560 for more):

Function.prototype.partial = function(/*args*/) {
    var a = [].slice.call(arguments, 0), f = this;
    return function() {
        var b = [].slice.call(arguments, 0);
        return f.apply(this, a.map(function(e) {
            return e === undefined ? b.shift() : e;
        }));
    }
};

["1", "2", "08"].map(parseInt.partial(undefined, 10))

这篇关于map + parseInt - 奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆