在這里開始 coder 學習 js 課程。我幾乎完成了高階函式課程,但被卡住了。我有一個物件,其中包含 250 個不同資訊的國家/地區。例子:
const countries = [
{
name: 'Afghanistan',
capital: 'Kabul',
languages: ['Pashto', 'Uzbek', 'Turkmen'],
population: 27657145,
flag:
'https://restcountries.eu/data/afg.svg',
currency: 'Afghan afghani'
},
{
name: '?land Islands',
capital: 'Mariehamn',
languages: ['Swedish'],
population: 28875,
flag:
'https://restcountries.eu/data/ala.svg',
currency: 'Euro'
}, etc.
我被要求撰寫一個函式來搜索每個國家/地區的名稱并回傳一個僅包含符合關鍵字條件的國家/地區的陣列。我很難過,感到非常失落。這是我所擁有的:
const keys = Object.keys(countries)
function categorizeCountries(keyword) {
for (let i = 0; i < keys.length; i ) {
let country = countries.name
if (country.includes(keyword)) {
console.log(countries.filter((country)
=> country.includes(keyword)))
} else {
console.log('Country not found')
}
}
return country
}
categorizeCountries('land')
scategorizeCountries('stan')
我確定問題出在我的條件陳述句中,但我不知道該怎么做。任何幫助是極大的贊賞。
uj5u.com熱心網友回復:
使用時,Object.keys
您只能獲取陣列的鍵。在您的情況下,只有 1、2。您想要的是值。然后使用過濾器原型很容易進行排序。
const countries = [
{
name: 'Afghanistan',
capital: 'Kabul',
languages: ['Pashto', 'Uzbek', 'Turkmen'],
population: 27657145,
flag:
'https://restcountries.eu/data/afg.svg',
currency: 'Afghan afghani'
},
{
name: '?land Islands',
capital: 'Mariehamn',
languages: ['Swedish'],
population: 28875,
flag:
'https://restcountries.eu/data/ala.svg',
currency: 'Euro'
}];
const countriesArray = Object.values(countries);
function categorizeCountries(keyword) {
console.log(countriesArray.filter(country => country.name.toLowerCase().includes(keyword.toLowerCase())))
}
categorizeCountries('af')
uj5u.com熱心網友回復:
這是一個簡短的片段,演示了如何使用.filter()
and .includes()
(@IvanaMurray 對要比較的字串的應用提出了一個很好的觀點,.toLowerCase()
為了簡單起見,我在這里省略了):
const countries = [
{
name: 'Afghanistan',
capital: 'Kabul',
languages: ['Pashto', 'Uzbek', 'Turkmen'],
population: 27657145,
flag:
'https://restcountries.eu/data/afg.svg',
currency: 'Afghan afghani'
},
{
name: '?land Islands',
capital: 'Mariehamn',
languages: ['Swedish'],
population: 28875,
flag:
'https://restcountries.eu/data/ala.svg',
currency: 'Euro'
}];
["land","stan","an"].forEach(s=>
console.log(countries.filter(c=>
c.name.includes(s)))
)
uj5u.com熱心網友回復:
您在國家/地區的回圈不正確(您不需要Object.keys
并且您省略了使用,i
您還必須將結果累積到陣列中)
function categorizeCountries(keyword) {
const result = [];
for (let i = 0; i < countries.length; i ) {
let { name } = countries[i];
if (name.includes(keyword)) {
console.log(name);
result.push(name);
} else {
console.log('Country not found')
}
}
return result;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/486823.html
標籤:javascript 目的 高阶函数
下一篇:如何清除反應div中的所有輸入