zoukankan      html  css  js  c++  java
  • 实现Math对象中max和min方法

    
    
        function mymin(num1) {
            if (arguments.length == 0) {
                // 没有参数
                return Infinity;
            } else if (arguments.length == 1) {
                // 一个参数
                return Number(num1);
            } else {
                // 至少两个参数
                // console.log(arguments);
                // 设最小值为第一个值
                var min = arguments[0];
                // 循环比较
                for (var i = 1; i < arguments.length; i++) {
                    if (arguments[i] < min) {
                        // 判断当前的值是否小于最小值,如果小于最小值,则将该值赋值给最小值
                        min = arguments[i];
                    }
                    // console.log(arguments[i]);
                }
                // 返回最小值
                return min;
            }
        }
        console.log(mymin());// Infinity
        console.log(mymin(1));// 1
        console.log(mymin('i love you'));// NaN 不需要去考虑
        console.log(mymin(true));// 1 不需要去考虑
        console.log(mymin(1, 3, 13, 12, 2, 5));// 13 
    
    
    
    function mymax(num1) {
            if (arguments.length == 0) {
                // 没有参数
                return -Infinity;
            } else if (arguments.length == 1) {
                // 一个参数
                return Number(num1);
            } else {
                // 至少两个参数
                // console.log(arguments);
                // 设最大值为第一个值
                var max = arguments[0];
                // 循环比较
                for (var i = 1; i < arguments.length; i++) {
                    if (arguments[i] > max) {
                        // 判断当前的值是否大于最大值,如果大于最大值,则将该值赋值给最大值
                        max = arguments[i];
                    }
                    // console.log(arguments[i]);
                }
                // 返回最大值
                return max;
            }
        }
        console.log(mymax());// -Infinity
        console.log(mymax(1));// 1
        console.log(mymax('i love you'));// NaN 不需要去考虑
        console.log(mymax(true));// 1 不需要去考虑
        console.log(mymax(1, 3, 13, 12, 2, 5));// 13 
  • 相关阅读:
    [loj6484]LJJ爱数书
    [loj3163]动态直径
    [loj2983]数树
    [luogu3785]文本校正
    [loj2572]字符串
    [loj3103]节日庆典
    [atARC118F]Growth Rate
    [atARC118E]Avoid Permutations
    [cf794G]Replace All
    [cf756E]Byteland coins
  • 原文地址:https://www.cnblogs.com/yess/p/12632558.html
Copyright © 2011-2022 走看看