如何在数组中将数字从字符串更改为整数

时间:2019-04-02 13:32:25

标签: javascript

我有一个问题,我必须取一个字符串数组(一些数字和一些字母)并删除零,将它们移到末尾,然后返回该数组。最终结果需要所有数字都是字符串中的整数。

我尝试映射数组并解析整数。除非传入的数组包含字母,否则此方法有效。然后所有字母都用NaN代替。我似乎无法设置仅对整数进行运算的条件。

var final = ["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0];

但应该是

var final = ["a","b","c","d",1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0]

我需要解析整数,但是无法获得map来完成我没有前面描述的问题。我也尝试过使用if语句,没有帮助。

5 个答案:

答案 0 :(得分:5)

如果转换是伪造的,则可以转换所有数字或尝试转换并采用该值。

var final = ["a", "b", "c", "d", "1", "1", "3", "1", "9", "9", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

console.log(final.map(v => +v || v));

零安全方法。

var final = ["a", "b", "c", "d", "1", "1", "3", "1", "9", "9", "0", 0, 0, 0, 0, 0, 0, 0, 0, 0];

console.log(final.map(v => isNaN(v) ? v : +v));

答案 1 :(得分:2)

您可以将isNaN()Array.prototype.map()Conditional (ternary) operator一起使用:

var final = ["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0];

final = final.map(i => isNaN(i) ? i : Number(i));

console.log(final);

答案 2 :(得分:1)

您想解析数字,但是如果使用条件,则返回原始元素(如果为NaN)

var final = array.map((x) => {
    var n = parseInt(x, 10);
    return !isNaN(n) ? x : n;
})

答案 3 :(得分:1)

您可以使用此:

var input = ["0", "a", "0", "b", "0", "0", "c", "d", "0", 0, "0", "1", "0", "1","3","0", "1","9","9", "0"];

var final = [...input.filter(s => s != 0), 
             ...input.filter(s => s == 0)
            ].map(s => isNaN(s) ? s : +s);

console.log(final);

答案 4 :(得分:1)

使用map()并在isNaN()上进行验证。

["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0]
.map(x => !isNaN(x) ? Number(x) : x)