我现在正在学习并从 reactjs 开始,我必须使用 API 制作一个基于权力的游戏的网页,我收到 api 数据,我可以在屏幕上打印 img、名称和年龄字符,但我需要按年龄对它们进行排序。
componentDidMount() {
fetch('https://api.got.show/api/show/characters/')
.then(res => res.json())
.then(json => {
this.setState({
items: json,
})
}).catch((err) => {
console.log(err);
});
}
render() {
const {items} = this.state;
return (
<div className="App">
<ul>
{items.filter(item=> item.age && item.age.age).map(item => (
<li key={item.id}>
<img src={item.image} alt="personajes" ></img> Name: {item.name} | age: {item.age.age}
</li>
))}
</ul>
</div>
);
}
导出默认应用;
这是我到现在为止得到的,我做了过滤器,因为有些 Angular 色不知道年龄,好吧,我想我必须使用一种排序,比如
items.sort((a,b) => a.item.age.age - b.item.age.age)
json 项目示例:
0
titles […]
origin […]
siblings […]
spouse […]
lovers []
plod 0
longevity []
plodB 0
plodC 0
longevityB []
longevityC []
culture […]
religion […]
allegiances […]
seasons []
appearances […]
_id "5cc0757c04e71a0010b86ac3"
name "Eddard Stark"
slug "Eddard_Stark"
image "https://vignette.wikia.n…wn/323?cb=20160730050722"
gender "male"
alive false
death 298
father "Rickard Stark"
house "House Stark"
first_seen "Winter Is Coming\""
actor "Sean Bean"
related […]
createdAt "2019-04-24T14:41:00.761Z"
updatedAt "2019-04-24T14:41:00.761Z"
__v 0
pagerank {…}
age :
name "Eddard Stark"
age 60
id "5cc0757c04e71a0010b86ac3"
但是我不知道我必须如何在我的代码中准确地编写它并使其工作,我还必须制作一个按钮,我可以在其中从小到大以及相反,如果你能帮助我,非常感谢,我昨天一整天都在用这个,很抱歉英语不是很好,希望你能理解一切:P
最佳答案
Here you can find more information regarding sorting arrays in javascript.
您可以链接一些数组操作,例如排序和过滤,因此解决方案是先过滤掉没有年龄的字符,然后对结果进行排序:
characters.filter(character => character.age).sort(compareFunction);
然后可以在你的 JSX 中使用它来按顺序显示没有年龄的字符:
return (
<div className="App">
<ul>
{items
.filter(item => item.age && item.age.age)
.sort((prev, next) => prev.age - next.age)
.map(item => (
<li key={item.id}>
<img src={item.image} alt="personajes" ></img> Name: {item.name} | age: {item.age.age}
</li>
))}
</ul>
</div>
);
这是一个删除没有年龄的字符并按升序和降序对年龄进行排序的工作示例:
function displayList(list) {
let html = '';
for (const person of list) {
html += `<li>${person.name}: ${person.age || "?"}</li>`;
}
document.getElementById('age-list').innerHTML = html;
}
const ageList = [{
name: "John",
age: 12
},
{
name: "Tim"
},
{
name: "Steven",
age: 40
},
{
name: "Marie",
age: 50
},
{
name: "Amy"
},
{
name: "Sheldon",
age: 5
},
{
name: "Charlotte",
age: 25
}
];
displayList(ageList);
document.getElementById('asc').onclick = () => {
const ascList = ageList.filter(item=> item.age).sort((prev, next) => {
return prev.age - next.age;
});
displayList(ascList);
}
document.getElementById('desc').onclick = () => {
const ascList = ageList.filter(item=> item.age).sort((prev, next) => {
return next.age - prev.age;
});
displayList(ascList);
}
<button id="asc">Ascending</button>
<button id="desc">Descending</button>
<ul id="age-list"></ul>
当然,您必须调整数据集和函数以适应您自己的数据集,以便它为您工作。
关于javascript - 我如何按年龄值对这个数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65197502/