js basics---function

Case 1: Find the maximum value of any number (the use of arguments)

<script>
    // 函数声明
    function getMax() {
    
    
        console.log(arguments);
        console.log('-----');
        var max = arguments[0]; //使max的值取数组第一个元素的值
        for (var i = 1; i < arguments.length; i++) {
    
    
            if (max < arguments[i]) {
    
     //将max与数组中其它元素相比
                max = arguments[i];
            }
        }
        console.log(max);
    }
    //函数调用
    getMax(9, 2, 8, 7, 22, 666, 5);
</script>

When you are not sure how many parameters are passed, you can use arguments to get them. In JavaScript, arguments are actually a built-in object of the current function. All functions have a built-in arguments object, and all the passed actual parameters are stored in the arguments object.

Case 2: Flip the array

<script>
   // 函数声明
    function reverse(arr) {
    
    
        var newArr = [];
        for (var i = arr.length - 1; i >= 0; i--) {
    
    
            newArr[newArr.length] = arr[i];
        }
        console.log(newArr);
    }
    //函数调用
    var arr = [9, 2, 8, 7, 22, 666, 5];
    reverse(arr);
</script>

ps: array [array.length] = new data

Case 3: Bubble sort

<script>
    // 函数声明
    function sort(arr) {
    
    
        for (var i = 1; i <= arr.length - 1; i++) {
    
    
            for (var j = 0; j <= arr.length - i - 1; j++)
                if (arr[j] > arr[j + 1]) {
    
     //此时结果从小到大顺序排列,如果改为<,则结果从大到小顺序排列
                    var temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
        }
        console.log(arr);

    }
    //函数调用
    var arr = [9, 2, 8, 7, 22, 666, 5];
    sort(arr);
</script>

Case 4: Determine leap year

<script>
    // 函数声明
    function judgeYear(year) {
    
    
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
    
    
            //能被4整除且不能被100整除  或者  能被400整除
            console.log('闰年');
        } else {
    
    
            console.log('平年');
        }
    }
    //函数调用
    judgeYear(2021);
</script>

Guess you like

Origin blog.csdn.net/pilgrim_121/article/details/112975022