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

如何从包含多种类型元素的数组中筛选出字符串元素?

问题解决:从数组中筛选字符串元素

你的代码返回空数组的原因是判断条件错误:element === String是把数组元素和String构造函数做全等比较,而数组里的字符串是原始类型的字符串字面量,和构造函数本身完全不是同一个东西,自然匹配不到任何元素。

正确写法(优先推荐)

用typeof判断元素类型,这是筛选原始类型字符串最稳妥的方式:

const newArray = [3, 'string A', 9, 'string B'];

console.log(
  newArray.filter((element) => typeof element === 'string')
)

执行后会输出期望的:

['string A', 'string B']

兼容字符串对象的写法(极少用到)

如果你的数组里存在用new String()创建的字符串对象,可以同时加上instanceof判断:

const newArray = [3, 'string A', new String('string C'), 9, 'string B'];

console.log(
  newArray.filter(element => typeof element === 'string' || element instanceof String)
)

内容的提问来源于stack exchange,提问作者Andres Hernandez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:35:30