gpt4 book ai didi

javascript - 返回类型 1、-1 和 0 在排序函数中的作用是什么?

转载 作者:行者123 更新时间:2023-11-29 18:08:35 24 4
gpt4 key购买 nike

这是作为实现对象排序问题的答案给出的工作代码,它工作得很好。由于我是 JavaScript 的新手,所以我不了解返回类型的确切作用。谁能解释一下?

var people= [
{
"f_name": "john",
"l_name": "doe",
"sequence": "0",
"title" : "president",
"url" : "google.com",
"color" : "333333",
}
// etc
];

function sortResults(prop, asc) {
people = people.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
showResults();
}

参数 'prop' 是需要进行排序的 propertyName,asc 是 bool 类型,如果为真则按升序排序,如果为假则按降序排序。

最佳答案

它是Array.sort,与jQuery 无关。请记住,jQuery 是另一个用 javascript 开发的库。

The MDN explains this already:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  1. If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.

  2. If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

  3. If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

  4. compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined

不强制只返回-11

关于javascript - 返回类型 1、-1 和 0 在排序函数中的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29467650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com