简体   繁体   English

排序 function 可以用于 JavaScript 中具有任意数字的数组吗?

[英]Can the sort function work for an array with arbitrary numbers in JavaScript?

I'm trying to get the set of numbers from a function (not included here) to be sorted in ascending order.我试图从 function (不包括在此处)中获取一组数字,以按升序排序。 But the sort function won't work anywhere.但是排序 function 不会在任何地方工作。 What am I doing wrong?我究竟做错了什么?

arrayX = [];

array.sort((x,y) => x-y);

I think the issue is that you are not setting the arrayX array equal to the sorted array.我认为问题在于您没有将arrayX数组设置为等于排序数组。

I tried this and it worked for me.我试过这个,它对我有用。

 let arr = [51, 12, 34, 63, 26, 84, 13]; let newArr = []; newArr = arr.sort((a, b) => a - b); console.log(newArr);

I made up the arr array to represent a bunch of random numbers for the test assuming the array you have also contains numbers, this should work.我组成了arr数组来代表一堆随机数进行测试,假设您拥有的数组也包含数字,这应该可以工作。

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

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