假設我有一個沒有特定順序的陣列,并且我想從該陣列中獲取給定型別的所有值(在本例中,讓我們使用字串)。
oldArray = [1, "2", {3: 4}, 5, "6", /7/];
/* ... */
newArray = ["2", "6"];
從邏輯上講,我會做這樣的事情:
newArray = [];
oldArray.forEach((element) => {
if (typeof element === "string") {
newArray.push(element);
}
});
(雖然不如 Python one-liner 優雅[value for value in oldArray if type(value) == str],但對我來說仍然足夠了。)
我的問題是:有沒有更有效的方法來做到這一點,或者這是一個最佳解決方案?
uj5u.com熱心網友回復:
使用Array#filter和typeof:
const oldArray = [1, "2", {3: 4}, 5, "6", /7/];
const newArray = oldArray.filter(e => typeof e === 'string');
console.log(newArray);
uj5u.com熱心網友回復:
您可以使用array.filter():
newArray = oldArray.filter(e => typeof e == "string")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345980.html
標籤:javascript 数组 排序 类型
上一篇:選擇總和-Javascript
