繁体   English   中英

如何从字符串数组中删除字母并转换为数字

[英]How to remove alphabets from array of string and convert to number

有人可以帮我吗,我需要从字符串数组中删除字母并将其转换为数字数组,这就是我所做的但没有做对。

 const fruits = [" 2", " 1", " 0", "remove this", " 1", " 2", " 0", " 0", " 1", " 0"]; let text = fruits.toString(); var f = text.replace(/[azAZ]/g, ""); var h = f.split(","); h.filter(n => n) console.log(h)

将它们转换为Numbers并删除那些不是的:

nums = fruits.map(Number).filter(x => !Number.isNaN(x))

您可以将字符串乘以 1 进行转换并检查它是否为数字

const fruits = [" 2", " 1", " 0", "remove this", " 1", " 2", " 0", " 0", " 1", " 0"];

console.log(fruits.filter((v)=> !Number.isNaN(v*1)).map((v)=> Number(v) * 1));

您可以使用 isNaN 函数来检查变量是否为数字。 这是代码:

const fruits = [" 2", " 1", " 0", "remove this", " 1", " 2", " 0", " 0", " 1", " 0"];

var nums=[]; // array for numbers

for( let i = 0; i < fruits.length ;i++){
    if(!isNaN(fruits[i])) // check if the value is number or not
    nums.push(parseInt(fruits[i]));//add numbers in array with int parsing
}

console.log(nums) //print the array of numbers only

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM