Write flip array with native JS

Time:2021-3-3

Method 1 (user defined function)

/*Steps: 1. Declare named function (formal parameter array)
               2. Variable storage = new array
               3. For sets the body of the loop
               4. Counter down traversal
               5. Return return value
               6. Variable storage = call function (argument)
               7. Console print variable output*/

function reverse(printArr) {
    var newArr = [];
    for (var i =  printArr.length  -1; I > = 0; I --) {// set the loop body, counter down traversal
        newArr[ newArr.length ]= printarr [i]; // index the total length of the new array, otherwise the direct storage will be blank
    }
    return newArr;
}
var printArr = reverse([1, 3, 5, 7, 9]);
console.log(printArr);  // [9, 7, 5, 3, 1]

 

Method 2 (built in object)

function sortArr(printArr) {
    printArr.reverse (); // variable object. Reverser() is a built-in JS method that can be called directly
    return printArr;
}
var printArr = sortArr([2, 4, 6, 8]);
console.log(printArr); // [8, 6, 4, 2]