javascript - JSX:按字母顺序对对象进行排序
问题描述
我有两个看起来像这样的函数:
const compare = (direction: string) => {
const alphabetize = (a, b) => {
if (direction === "alpha") {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
} else if (direction === "reverseAlpha") {
if (a.name > b.name) {
return -1;
}
if (a.name < b.name) {
return 1;
}
}
return 0;
};
};
const sortAlphabetically = () => {
setState(state => ({
...state,
items: items.sort(compare("alpha"))
}));
};
我需要能够以compare
某种方式将字符串传递给函数,告诉它以哪种方式对字母进行排序(按字母顺序,或按字母顺序倒序)。
但是这个方法不起作用,因为alphabetize
从来没有这样调用过。我错过了什么?
谢谢!
解决方案
[编辑] 您必须在 compare 函数中调用 alphabetize,如下所示:
const compare = () => {
const alphabetize = () => {
...stuff
}
alphabetize()
}
附带说明: JS 带有排序和反向功能:
var sortAlphabets = (text, direction) =>
direction === "reverseAlpha"
? text
.split("")
.sort()
.reverse("")
.join("")
: text
.split("")
.sort()
.join("");
推荐阅读
- html - 使用 display: inline 添加第二个元素后无法居中 h1;
- kotlin - 带有 Coroutines 中缀的构建器模式
- firebase - 我想导航到另一个页面并使用 Firestore 数据进行解析,但是当我使用 MaterialPageRoute 时该怎么做?
- sql - 为什么 SQL 抱怨对连接键的引用不明确?
- d3.js - D3 使用箭头函数和 d3 每个迭代器
- javascript - 无法链接 useEffects 以使用来自先前效果的更新状态
- tensorflow - COCO json 注解转 YOLO txt 格式
- git - 从 Github 存储库获取最新数据 - Github 桌面
- sql - 在 pyspark 中查找过去 n 天内出现的 id
- java - Spring Boot 2 获取客户端时区