我想使用這個 API https://restcountries.com/#api-endpoints-v3-all
這是鏈接 https://restcountries.com/v3.1/all
在此物件中,國家/地區未按字母順序排序。我怎樣才能在函式內做到這一點?
const btn = document.querySelector("button");
const output = document.querySelector("#output");
const intake = document.querySelector("input");
const url = "https://restcountries.com/v3.1/all";
let myData = {};
fetch(url).then(function (res) {
return res.json()
}).then(function (data) {
myData = data;
buildSelect(data);
})
function buildSelect(d) {
let select = document.createElement('select');
d.forEach(function (item, index) {
let option = document.createElement('option');
console.log(item,index);
option.value = index;
option.textContent = item.name.common;
select.appendChild(option);
})
document.querySelector('body').appendChild(select);
}
代碼屬于 Laurence Svekis,我正在學習他的課程,但在他的版本中,它已經按 API 端排序了。
謝謝!
uj5u.com熱心網友回復:
如果其余代碼有效,那么唯一的修改是在創建選項的迭代之前進行排序......
function buildSelect(data) {
sortedData = data.sort((a,b) => {
const aName = a.name.common;
const bName = b.name.common;
return (aName < bName) ? -1 : (aName > bName) ? 1 : 0;
});
let select = document.createElement('select');
sortedData.forEach(function (item, index) {
// ...
uj5u.com熱心網友回復:
您可以.forEach在buildSelect函式內呼叫之前對資料進行排序。我建議使用localeCompare來自https://restcountries.com/v3.1/all的資料中的一些常用名稱進行排序,所有包含非 ASCII 字符。
快速示例
d
.sort((a, b) => ('' a.name.common).localeCompare(b.name.common))
.forEach(function (item, index) {
let option = document.createElement('option');
console.log(item,index);
option.value = index;
option.textContent = item.name.common;
select.appendChild(option);
})
// If you must support IE you could replace the sort with...
// .sort(function(a, b) { return ('' a.name.common).localeCompare(b.name.common) }));
顯示代碼片段
const btn = document.querySelector("button");
const output = document.querySelector("#output");
const intake = document.querySelector("input");
const url = "https://restcountries.com/v3.1/all";
let myData = {};
fetch(url).then(function (res) {
return res.json()
}).then(function (data) {
myData = data;
buildSelect(data);
});
function buildSelect(d) {
let select = document.createElement('select');
d
.sort((a, b) => ('' a.name.common).localeCompare(b.name.common))
//.sort(function(a, b) { return ('' a.name.common).localeCompare(b.name.common) })
.forEach(function (item, index) {
let option = document.createElement('option');
//console.log(item,index);
option.value = index;
option.textContent = item.name.common;
select.appendChild(option);
})
document.querySelector('body').appendChild(select);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394998.html
標籤:javascript 接口
