0

I try to use code from this Move an array element from one array position to another to move arrays position

But why when i will move last to first so I get a empty array

i do like this...

my_array.move(my_array_length,0);

Demo : http://jsfiddle.net/Jsu7R/

Community
  • 1
  • 1
l2aelba
  • 20,261
  • 20
  • 97
  • 133

2 Answers2

4

Since javascript arrays are indexed from 0 upwards, your code:

my_array.move(my_array_length,0);

will need to change to :

my_array.move(my_array_length-1,0);

The length of your array has 5 elements, but the last element has an index of 4.

Lee Taylor
  • 7,155
  • 14
  • 29
  • 44
  • 2
    You might also consider changing the function to either pferform a no-op or throw an error if the old index is outside the bounds of the array – roryf Dec 06 '12 at 13:28
2

The method "move" from the reference page gets old_index, new_index parameters. You supply the array's length as the first parameter, but your array has no element at this position.

If you call "move" with these parameters:

my_array.move(my_array_length - 1,0)

it will work as expected

Anton N
  • 502
  • 1
  • 4
  • 9