簡體   English   中英

將 for 循環變成 foreach 循環不起作用

[英]Turn a for loop into a foreach loop not working

我正在嘗試將for循環變成forEach循環,但它似乎不起作用......

這是我的代碼:

const townDataURL = "[some link I probably can't disclose...]"
const towns2get = [
    "Preston",
    "Fish Haven",
    "Soda Springs"
]

fetch(townDataURL)
    .then((response) => {
        return response.json()
    })
    .then((jsonData) => {
        const towns = jsonData["towns"].filter((item) => {
            // for (let i = 0; i<towns2get.length; i++) {
            //     if (item.name == towns2get[i]) {
            //         return item
            //     }
            // }
            return (towns2get.forEach(elem => {
                return ( (item.name == elem) ? (item) : "Hello?" )
            }))
        })
        console.log(towns)
    })

當我運行注釋代碼時,它給了我這個:

(3) [{…}, {…}, {…}]
0: {name: "Fish Haven", photo: "fishhaven.jpg", motto: "This is Fish Heaven.", yearFounded: 1864, currentPopulation: 501, …}
1: {name: "Preston", photo: "preston.jpg", motto: "Home of Napoleon Dynamite.", yearFounded: 1866, currentPopulation: 5204, …}
2: {name: "Soda Springs", photo: "sodasprings.jpg", motto: "Historic Oregon Trail Oasis. The Soda is on Us.", yearFounded: 1858, currentPopulation: 2985, …}
length: 3
__proto__: Array(0)

這正是我想要的,但我想簡化我的代碼......我現在擁有的是:


[]
length: 0
__proto__: Array(0)

我做了一些調試,我知道我的條件語句與三元運算符工作正常,它正在返回一個值......但我似乎無法弄清楚為什么它沒有將它返回到filter方法...

這樣不行嗎? 或者我是否必須以某種方式將forEachfilter放在一起?

感謝您的任何幫助!

這里更好的方法是在過濾方法中使用.includes function

const townDataURL = "[some link I probably can't disclose...]"
const towns2get = [
    "Preston",
    "Fish Haven",
    "Soda Springs"
]

fetch(townDataURL)
    .then((response) => {
        return response.json()
    })
    .then((jsonData) => {
        const towns = jsonData["towns"].filter((item) => {
            if(towns2get.includes(item.name) > -1) return true;
            else return false;
        })
        console.log(towns)
    })

Cris G 給了我答案:

.forEach()不返回任何內容,因此您的.filter()回調為每個元素返回undefined ,這是一個錯誤的值。 使用filter(item => towns2get.includes(item.name))Chris G

所以代碼應該是:

const townDataURL = "[some link I probably can't disclose...]"
const towns2get = [
    "Preston",
    "Fish Haven",
    "Soda Springs"
]

fetch(townDataURL)
    .then((response) => {
        return response.json()
    })
    .then((jsonData) => {
        const towns = jsonData["towns"].filter(item => towns2get.includes(item.name))
        console.log(towns)
    })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM