You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

从字符串数组提取数字并转换为数字数组的解决方案

你的代码存在几个问题,导致无法得到正确结果:

  1. 将数组转为字符串再处理会引入无效空元素:fruits.toString()把数组转为逗号分隔的字符串,替换字母后原"remove this"的位置会变成空内容,split后得到包含空格的无效元素。
  2. filter操作未保存结果:h.filter(n => n)返回了过滤后的新数组,但你没有将其赋值给变量,原数组h并未被修改。
  3. 未完成字符串到数字的转换:最终得到的仍是字符串数组,而非目标数字数组。

方案一:正则匹配提取有效数字

遍历数组元素,用正则匹配纯数字内容,转换为数字后过滤无效项:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:45:36