[英]Sorting an Array numerically in Javascript
Hello, 你好,
i am new to stackoverflow and coding so I hope you don't mind me asking such a trivial question. 我是stackoverflow和编码的新手,所以希望您不要介意我问这样一个琐碎的问题。
I learned that sorting an array numerically is done as follows. 我了解到,对数组进行数字排序的步骤如下。 I am also aware of the simpler ES6 version.
我也知道更简单的ES6版本。
var ax = [], bx = []; function sortNumber (a, b) { ax.push(a); bx.push(b); return ab; } var numArray = [140000, 104, 99, 2]; numArray.sort(sortNumber); console.log('array=' + numArray); console.log('a=' + ax); console.log('b=' + bx);
What i don't understand is, why for example in my Code-Example in the sortNumber function 我不明白的是,为什么例如在我的代码示例中的sortNumber函数中
a = [140000, 104, 140000, 104, 99] and b = [99, 99, 2, 2, 2] ? a = [140000,104,140000,104,99]和b = [99,99,2,2,2] ?
Can someone tell my how a and b are determined? 有人可以告诉我如何确定a和b吗?
Thanks in advance! 提前致谢!
Can someone tell my how a and b are determined?
有人可以告诉我如何确定a和b吗?
It's entirely up to the JavaScript engine's implementation of sort
. 这完全取决于JavaScript引擎的
sort
实现。 All that the specification tells us is that they'll be entries from the array that need to be compared so the sort
algorithm can do its job. 规范告诉我们的是,它们将是数组中需要比较的条目,以便
sort
算法可以完成其工作。
If you like, you can see V8's implementation here , which is a variation of a TimSort . 如果愿意,您可以在这里看到V8的实现,它是TimSort的变体。 (V8 is the JavaScript engine used in Chromium, Chrome, Brave, and Node.js.)
(V8是Chromium,Chrome,Brave和Node.js中使用的JavaScript引擎。)
I should note that V8 doesn't use the values for a
and b
that are shown in your question, it uses 104
, 99
, and 2
for a
and 140000
, 104
, and 99
for b
. 我要指出,V8不使用值
a
和b
是在你的问题中所示,它采用104
, 99
,和2
为a
和140000
, 104
和99
的b
。
You can see which ones the JavaScript engine in your current browser uses here: 您可以在此处查看当前浏览器中的JavaScript引擎使用了哪些引擎:
var avalues = []; var bvalues = [] function sortNumber (a, b) { console.log("a = " + a + ", b = " + b); avalues.push(a); bvalues.push(b); return ab; } var numArray = [140000, 104, 99, 2]; numArray.sort(sortNumber); console.log("done, result:", numArray.join(", ")); console.log("a values: ", avalues.join(", ")); console.log("b values: ", bvalues.join(", "));
I think your question is how this sorting function is working. 我认为您的问题是此排序功能的工作方式。
numArray.sort(sortNumber)
; numArray.sort(sortNumber)
; it will call on all the elements of the array with each other (You care comparing each element). a - b > 0
, a is greater than b. a - b > 0
,则a大于b。 if a - b < 0
, b is greater than a. a - b < 0
,则b大于a。 if a - b = 0
, both are equal. a - b = 0
,则两者相等。 This condition will get checked on all the elements [140000, 104, 99, 2]. Hope this helps. 希望这可以帮助。
在这种情况下,我只是使用lodash。
_.sortBy([140000, 104, 99, 2]) // => [2, 99, 104, 140000]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.