简体   繁体   English

我的updateState函数中的参数来自哪里?

[英]Where are the parameters coming from in my updateState reactjs function?

I'm just starting JS and React using the fullstack.io book. 我只是使用fullstack.io书来启动JS和React。

In the book, there is a section of code: 书中有一段代码:

updateState: function () {
    const products = Data.sort((a, b) => {
        return b.votes - a.votes;
}

Now everytime the updateState function is called in the code samples, there are no parameters passed in... so how would the "a" & "b" parameters used in the Data.sort be populated? 现在,每次在代码示例中调用updateState函数时,都不会传递任何参数...那么,如何填充Data.sort中使用的“ a”和“ b”参数?

Thank you. 谢谢。

I'm not sure what Data is but let's assume it's an array. 我不确定什么是Data ,但让我们假设它是一个数组。

Array.prototype.sort is a function that takes a comparator callback function (a, b) => { ... } . Array.prototype.sort是一个带有比较器回调函数(a, b) => { ... }函数。
The function compares elements a and b . 该函数比较元素ab
If the function returns a number less than 0, a comes before b (ascending order). 如果函数返回的数字小于0,则ab之前(升序)。
Otherwise b comes before a (descending order). 否则ba (降序)之前。

The key takeaway is that a and b are passed by sort under the hood. 关键要点是ab在引擎盖下按sort传递。 You only need to worry about providing the callback which determines the sort order. 您只需要担心提供确定排序顺序的回调。

For example: 例如:

let arr = [2, 4, 7, 1]

arr.sort((a, b) => a - b) // => [1, 2, 4, 7]

arr.sort((a, b) => b - a) // => [7, 4, 2, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM