DEV Community

Cover image for TS - 使用其他語法替代跳出 forEach 迴圈這件事
FakeStandard
FakeStandard

Posted on • Edited on

TS - 使用其他語法替代跳出 forEach 迴圈這件事

使用其他語法來替代中止 forEach 以達成目的

前篇談到如何中止 forEach 迴圈,這篇將會演示如何使用其他語法達到類似結果的做法。而其他語法則是在上篇中記錄基本用法,這篇將不再贅述。

從陣列中檢查是否有符合條件的元素,我們可以使用 some 方法來取得檢查結果

const arr = [1, 2, 3]

const res = arr.some(val => val === 2)
console.log(res)

// output
// true

const res = arr.some(val => val === 5)
console.log(res)

// output
// false
Enter fullscreen mode Exit fullscreen mode

或者使用 every 檢查陣列中是否有元素不符合條件

const arr = [18, 20, 26]

const res = arr.every(val => val < 30)
console.log(res)

// output
// true

const res = arr.every(val => val > 20)
console.log(res)

// output
// false
Enter fullscreen mode Exit fullscreen mode

如果原本就了解 someevery 方法,上述兩種執行對你來說是小菜一碟

So, What about nested ? 如何檢查雙陣列是否符合指定條件?

第一,假設要從兩個陣列中,檢查是否具有任一的相同元素,並且返回布林值。透過 some 方法來迭代兩個陣列,每次完成內層迭代時必須返回結果給外層,外層接收值之後會決定是否中斷迭代返回結果,假設內層從不返回任何值給外層 callback 函數,那麼外層永遠只會返回 false。

const arr1 = [1, 2, 3]
const arr2 = [2, 3, 4]

const res1 = arr1.some(v1 => {
    const res2 = arr2.some(v2 => {
        return v1 === v2
    })

    return res2 // 必須返回結果給上層
})
Enter fullscreen mode Exit fullscreen mode

倘若檢查條件沒有太複雜,可將程式碼簡化如下

const res = arr1.some(v1 =>
    arr2.some(v2 =>
        v1 === v2
    )
)
Enter fullscreen mode Exit fullscreen mode

第二,從兩個未排序的陣列中,檢查兩陣列是否為相同元素的陣列,所有元素皆相同但位置可以不同,例如 1,2,32,1,3 符合條件,兩陣列內都有 1, 2, 3 三個元素,雖然位置擺放不同卻不影響結果。

const arr1 = [1, 2, 3, 4, 5]
const arr2 = [3, 5, 1, 4, 2]

const res1 = arr1.every(v1 => {
    const res2 = arr2.some(v2 => {
        return v1 === v2
    })

    return res2
})
Enter fullscreen mode Exit fullscreen mode

利用 every 的特性以及搭配 some 方法,當內層有任一元素與外層元素相同時,內層會返回 true 給外層,外層接收到結果後會繼續下一次迭代;若內層迭代在某次返回 false,外層接收到此結果後,every 會直接返回 false 結果並中止所有迭代。

經過以上的範例後,我們應根據不同的情況去選擇適當的語法使用,以有效地處理商業邏輯。現在,有沒有覺得在 forEach 中使用 try catch 有點殺雞焉用牛刀?


Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or follow my GitHub ⭐ I'd appreciate it.


Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay