0

I've created an array that I now want to reverse. The array should display every number from the number specified down to 0.

I've tried using the reverse() method in various ways but it either misses out every other number in the array or returns nothing at all?

In the code below the else if statement is where the array wants reversing.

Is there a way to use the reverse() method on the array here or an alternative way to do this?

Thanks

function myFunc() {

  var x = Math.floor(Math.random() * 100);
  var counter = [];
  var start = 0;
    if (x > 40) { 
      start = 40;
      } else { 
      start = 0; }

  for (var i = start; i < x; i++) {
    if (x > 40 && i % 2 == 1) {
        counter.push(i);
    } else if (x < 40) {
        counter.push(i).reverse(); //reverse here returns nothing
        counter.reverse();         //reverse here returns every other number only 
    }
  }

   return counter + ',' + x;

}

 console.log(myFunc())
4

3 回答 3

0

我创建了一个我现在想要反转的数组。该数组应显示从指定数字到 0 的每个数字。

如果这是问题所在,那么您可以像这样更轻松地解决它:

var x = Math.floor(Math.random() * 100);
var counter = [];
var end = (x > 40 ? 40 : 0);
while (end <= x) {
    counter.push(x);
    --x;
}
return counter;

演示

先试后买

但是,您的代码会执行其他操作,但您可以像这样调整它:

while (end <= x) {
    if ( ((40 < x) && (1 == x % 2)) || (40 > x)) {
        counter.push(x);
    }
    --x;
}
于 2013-09-11T10:46:36.947 回答
0
......
for (var i = start; i < x; i++) {
    if ((x > 40 && i % 2 == 1) || x < 40) {
        counter.push(i);
    }
}

if(x<40)
    counter.reverse(); 

return counter; 
}

应该像这样工作..(除非我误解了你的问题?)

于 2013-09-11T10:42:35.537 回答
0

http://jsfiddle.net/aLUfh/2/

var x = Math.floor(Math.random() * 100);
var counter = [];

for (i = 0; i < x; i++) {
    counter.push(i);
}

counter.reverse();
$('#Xis').html(x);
$('#outcome').html(counter + ',' + x);
于 2013-09-11T10:47:14.797 回答