繁体   English   中英

有没有一种有效的方法可以从 JavaScript 中的数组中获取某种类型的所有值?

[英]Is there an efficient way to get all values of a certain type from an array in JavaScript?

假设我有一个没有特定顺序的数组,并且我想从该数组中获取给定类型的所有值(在本例中,让我们使用字符串)。

oldArray = [1, "2", {3: 4}, 5, "6", /7/];
/* ... */
newArray = ["2", "6"];

从逻辑上讲,我会做这样的事情:

newArray = [];
oldArray.forEach((element) => {
  if (typeof element === "string") {
    newArray.push(element);
  }
});

(虽然它不像 Python 单行[value for value in oldArray if type(value) == str]那样优雅,但对我来说仍然足够了。)


我的问题是:有没有更有效的方法来做到这一点,或者这是一个最佳解决方案?

您可以使用array.filter()

newArray = oldArray.filter(e => typeof e == "string")

使用Array#filtertypeof

 const oldArray = [1, "2", {3: 4}, 5, "6", /7/]; const newArray = oldArray.filter(e => typeof e === 'string'); console.log(newArray);

我认为这是最简单的你会得到🤣

暂无
暂无

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

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