For example, in
function swap ( arr, i1, i2 )
{
// swaps elements at index i1 and i2
// in the array arr
var temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
function reverse_array ( arr )
{
// reverse the order of the elements in array arr
var i1 = 0, i2 = arr.length;
while ( i1 != i2 && i1 != --i2 ) swap(arr,i1++,i2);
}
var myArray = [1, 2, 3, 4];
reverse_array(myArray);
myArray.forEach(function(elem) { $('#mydiv').append(elem + ' ') });
the only way I know of implementing a swap
function for elements of an array is to pass in the array in. However, that seems inefficient. There must a way of implementing a straight-up swap
function for variables of any type. I guess my question really boils down to:
What is the most efficient way of implementing a swap function in JavaScript???
Is there a way of "boxing" (to use a C# term) to variables before passing them into a classic function swap ( a, b ) { temp = a; a = b; b = temp; }
procedure?