如何从字符串数组中去除字母并转换为数字数组?
从字符串数组提取数字并转换为数字数组的解决方案
你的代码存在几个问题,导致无法得到正确结果:
- 将数组转为字符串再处理会引入无效空元素:
fruits.toString()把数组转为逗号分隔的字符串,替换字母后原"remove this"的位置会变成空内容,split后得到包含空格的无效元素。 filter操作未保存结果:h.filter(n => n)返回了过滤后的新数组,但你没有将其赋值给变量,原数组h并未被修改。- 未完成字符串到数字的转换:最终得到的仍是字符串数组,而非目标数字数组。
方案一:正则匹配提取有效数字
遍历数组元素,用正则匹配纯数字内容,转换为数字后过滤无效项:
const fruits = [" 2", " 1", " 0", "remove this", " 1", " 2", " 0", " 0", " 1", " 0"]; const numberArray = fruits .map(item => { // 去除前后空格后匹配纯数字 const numMatch = item.trim().match(/^\d+$/); // 匹配成功则转数字,否则返回null return numMatch ? Number(numMatch[0]) : null; }) .filter(num => num !== null); console.log(numberArray); // 输出: [2, 1, 0, 1, 2, 0, 0, 1, 0]
方案二:利用Number转换过滤无效值
通过Number()转换字符串,纯字母内容会转为NaN,直接过滤这些无效值:
const fruits = [" 2", " 1", " 0", "remove this", " 1", " 2", " 0", " 0", " 1", " 0"]; const numberArray = fruits .map(item => Number(item.trim())) .filter(num => !isNaN(num)); console.log(numberArray); // 输出: [2, 1, 0, 1, 2, 0, 0, 1, 0]
内容的提问来源于stack exchange,提问作者joe
相关产品推荐
相关产品推荐

