我正在尝试按“正文”属性对一组评论对象进行排序。
我正在尝试运行以下命令(console.log(comment) 成功显示数组)但是当我对它进行排序时,我只是得到相同的数组 - 即使在将其定义为 sortedArray
变量。
我见过一些类似的问题,但与我尝试实现的箭头函数语法不太一样。
下面是我的代码:
function sortComments() {
$("#sort_comments").on("click", function(e) {
e.preventDefault();
var id = this.dataset.linkid
fetch(`/links/${id}/comments.json`)
.then(r => r.json())
.then(comments =>
comments.sort(function(a, b) {
return a.body - b.body;
})
);
});
}
感谢您的帮助。
最佳答案
这里可能发生的是 body
属性是一个字符串而不是一个数字,因此该减法的结果返回 NaN
,如果是这种情况,顺序Array
不会改变。
为了比较 2 个不同的字符串,您可能需要使用 localeCompare
,如下所示:
function sortComments() {
$("#sort_comments").on("click", function (e) {
e.preventDefault();
var id = this.dataset.linkid
fetch(`/links/${id}/comments.json`)
.then(r => r.json())
.then(comments =>
comments.sort(({body: a}, {body: b}) => a.localeCompare(b))
);
};
}
关于javascript - 按属性对 JavaScript 对象排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54430845/