我有一個js陣列,我需要得到子陣列,其中只有那些以 "outh2 "字串開始的專案。
這個解決方案給出了結果,但我正在尋找一個有效的或內置的函式,如果有的話?
。const result = ["oauth2. Hubspot1", "oauth1.Hubspot", "oauth2. Hubspot", "oauth2.HubSpot", "something else"】。] filter(function(key) {
if (key.indexOf("oauth2."/span>) == 0) return true。
});
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
預期值是
["oauth2.Hubspot1","oauth2.Hubspot","oauth2.Hubspot"]
uj5u.com熱心網友回復:
你可以使用startsWith函式:
[
"oauth2.Hubspot1"/span>。
"oauth1.Hubspot"。
"oauth2.Hubspot"。
"oauth2.Hubspot"。
"something else"。
].filter(key => key.startsWith("oauth2;)
uj5u.com熱心網友回復:
對于少于10萬個專案的陣列,你的解決方案應該是 "足夠好 "的。
。const arr = Array. from({length: 100000}, (_, i) => `oauth2.Hubspot${i}`)。)
const t0 = performance.now()
const res0 = arr.filter(function(key) {
if (key.indexOf("oauth2."/span>) == 0) return true。
});
const t1 = performance.now()
const res1 = arr.filter(span class="hljs-params">key => key。 startsWith("oauth2.") )。
const t2 = performance.now()
console.log(`Original: ${t1-t0}ms`)。)
console.log(`startsWith: ${t2-t1}ms`;)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/306896.html
標籤:
下一篇:用物件轉換陣列
