簡體   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