在javascript中需要一个函数来交换数组中的2个元素

时间:2010-04-14 13:31:39

标签: javascript function arrays elements swap

                      一个交换两个数字的程序                      

        /*
        /*
        Function to swap two numbers.
        Function takes an argument which is an array of two elements.
        Function returns a new array containing the same two elements
                       as the argument array but in reverse order.
        */

        function swap(anArray)           
        {
        // declare and initialise a variable to hold the length of the 
                          argument array
            var length = anArray.length;

            //declare an array to be returned by the function
            var returnArray = new Array(length);

            //copy each element of the argument array to the  
                                  return array
            for (var i = 0; i < length; i = i + 1)
            {
                returnArray[i] = anArray[i];
            }


        var anArray [0] = 250;
        var anArray [1] = 100;

        var tempArray [0] = 0;
        var tempArray [1] = 0;

        tempArray [0] = anArray [1];
        tempArray [1] = anArray [0];


        }

        document.write('A program to swap two numbers.');

        //  PLACE YOUR CODE FOR THE MAIN PROGRAM HERE

        var anArray = [250,100];

        // Display the original array values,
        document.write('The original array was ' + anArray[i] + '<BR>');

        // invoke swap() with two element array argument
        function swap(anArray);

        // display final array values
        document.write('This array now becomes ' + returnArray[i] + '<BR>');

    </SCRIPT>
</HEAD>
<BODY>

</BODY>

3 个答案:

答案 0 :(得分:10)

你的代码非常漫长。如果数组总是包含两个元素,为什么不这样做?

function swap(arr) {
    return [arr[1], arr[0]];
}

此外,调用该函数的正确方法是:

arr = swap(arr);

如果您希望函数修改其参数,请改为:

function swap(arr) {
    var tmp = arr[1];
    arr[1] = arr[0];
    arr[0] = tmp;
}

...另外,在数组上有一个名为reverse的内置方法:

arr.reverse();

答案 1 :(得分:0)

稍微偏离主题,但是这个Array方法以最快的方式交换其数组的两个元素(一般情况):

// swaps elements at index i and j in array this
// feature detection for destructuring assignment
Array.prototype.swap = (function () {
    var i=0, j=1;
    try { [i,j]=[j,i]; }
    catch (e) {}
    if(i) {
        return function(i,j) {
            [this[i],this[j]] = [this[j],this[i]];
            return this;
        }
    } else {
        return function(i,j) {
            var temp = this[i];
            this[i] = this[j];
            this[j] = temp;
            return this;
        }
    }
})();

答案 2 :(得分:0)

    function swap(anArray) { 
        var length = anArray.length; 
        var returnArray = new Array(length); 
        for (var i = 0, j = length - 1; i < length; i++, j--) { 
            returnArray[j] = anArray[i]; 
        } 
        return returnArray;
    }