[英]I can't sort numbers in an array (tried everything that was written here, stil doesnt work)
I've been doing a little game in JS and I got to the point, when I have an array with 4 numbers (one of them is the correct result, the other 3 are random). 我一直在用JS做一个小游戏,当我有一个包含4个数字的数组(其中一个是正确的结果,其他三个是随机的)时,我明白了。 I need to sort them (ascending) but nothing seems to work.
我需要对它们进行排序(升序),但似乎没有任何效果。 I tried E6 and E2015 funcitons that are mentioned here but nothing.
我尝试了此处提到的E6和E2015函数,但是什么也没有。 I¨M including my code plus code from the console so you would see.
我将包括我的代码以及来自控制台的代码,以便您看到。 Do you know how to deal with it or where is the problem?
您知道如何处理它或问题在哪里? Thank you for your time.
感谢您的时间。
//this is the code i have:
var rnum1 = generateRandomNumber1 ();
var rnum2 = generateRandomNumber2 ();
var rnums = [rnum1, rnum2];
var rnumsSort = rnums.sort(function(a, b){return b-a});
var data= generateRandomOperatorAndCorrectResult(rnumsSort[0],rnumsSort[1]);
//data=["+", [5]]
var operator=data[0];
var corResult = data[1][0][0];
var ranResult =[data[1][0][1],data[1][0][2],data[1][0][3]];
var allResults = data[1];
var sortAllResults = allResults.sort(function(a,b){
return a - b});
var mes=alert(sortAllResults);
//I'm sure all of my function are working because it alerts the actual 4 numbers in the array (var allResults = data[1]) but it doesnt do the sort method
function generateRandomOperatorAndCorrectResult (num1, num2) {
var operators = [{
sign: "+",
method: function(rnum1,rnum2){ return rnum1 + rnum2; } },
{
sign: "*",
method: function(rnum1,rnum2){ return rnum1 * rnum2; } },
{
sign: "-",
method: function(rnum1,rnum2){ return rnum1 - rnum2; }
}];
var results = [];
var selectedOperator = Math.floor(Math.random()*operators.length);
var randomOperator = operators[selectedOperator].sign;
var correctResult = (operators[selectedOperator].method(num1, num2)); //pass the numbers to the methods
results.push(correctResult);
var randomResult = generateRandomResults(3);
var result = results.concat(randomResult);
return [randomOperator, [result]];
}
The problem is you're trying to sort an array of arrays. 问题是您要对数组数组进行排序。 When you declare other variables, you're going like this:
当声明其他变量时,将如下所示:
data[1][0][0]
This means that data
is an array, containing at least one array, which contains at least one array, which contains your data. 这意味着
data
是一个数组,包含至少一个数组,其中包含至少一个数组,其中包含您的数据。
However, when you declare allResults
(the array you want to sort), you set it one level up - you're setting it equal to an array containing an array, which contains your data. 但是,在声明
allResults
(要排序的数组)时,将其设置为上一级-将其设置为等于包含包含数据的数组的数组。 So you're actually sorting an array of arrays. 因此,您实际上是在对数组进行排序。
To fix this, simply declare allResults
like so: 要解决此问题,只需像这样声明
allResults
:
var allResults = data[1][0];
And then you will be comparing numbers, not arrays. 然后,您将比较数字,而不是数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.