Returning an array from a function with JavaScript. Reversing the order of the returned array

StackOverflow https://stackoverflow.com/questions/22470753

  •  16-06-2023
  •  | 
  •  

Pregunta

//draw the points
//var pointOrigins1=new Array();
//pointOrigins1 = drawPoints(canvas, context);
//var pointOrigins2=new Array();
//pointOrigins2 = pointOrigins1;
//pointOrigins2.reverse();
//Place a donut on each point origin
//circlePointOrigins(canvas,context,pointOrigins1);
console.log(drawPoints(canvas, context));

//console.log(pointOrigins1);
//console.log(pointOrigins2);

//renderCheckers(canvas,context,pointOrigins1,pointOrigins2,checkers1,checkers2,initiator);





function drawPoints(canvas,context) {
    pointOrigins.push(drawTriangle(50+i,550,false,'black',canvas,context));
    return pointOrigins;
}

The code below is run. In the above code I have commented out what I have been trying that is not working yet. My goal is to reverse the returned array that is returned from the drawPoints function:

console.log(drawPoints(canvas, context));

Runs and the output looks like in the console:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

I'm noticing that in the render event of gameview if I call:

var pointOrigins1=new Array();
pointOrigins1 = drawPoints(canvas, context);
var pointOrigins2=new Array();
pointOrigins2 = pointOrigins1;
pointOrigins2.reverse();

the reverse has no effect at all. I intend to use the .reverse function for use with JavaScript arrays but right now that is not working.

I'm not sure how to resolve the .reverse problem yet but I think it might have something to do with how I am returning my functions.

Thank you for posting....

¿Fue útil?

Solución

Array.prototype.reverse modifies the array it's given. In your example both pointOrigins2 and pointOrigins1 end up containing the same reversed array. Try changing the lines

var pointOrigins2=new Array();
pointOrigins2 = pointOrigins1;

to

var pointOrigins2=pointOrigins1.slice();

Otros consejos

Here is another way to reverse an array using this function! Hope it helps!

var reverseArray = function(InputArray){
  for(i=0; i<= Math.floor((InputArray.length / 2) -1); i++){
    var a = InputArray[i];
    var b = InputArray[(InputArray.length -1) - i];
    InputArray[(InputArray.length -1) - i] = a;
    InputArray[i] = b;
  }
  return InputArray;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top