提问者:小点点

如何检测JS参数是否有多余的文本?[副本]


如果我有一个带有如下参数(或参数)的函数:

check('red', 'blue', 'arial')

我想知道的是你能不能有这样的文字:

check(background:'red', color:'blue', font:'arial')

在函数中,我有一个if语句,所以如果参数或参数有背景:在它之前,它将背景更改为背景之后的参数:

    function check(one, two, three){
        if (one==background:one){
           document.body.style.background= one ;
            }
        }  

我知道这行不通,你会怎么做呢?

我可以使用if语句,但对它进行编码以检测参数之前是否有“background:”吗?这是可能的,还是有更好的做法?如果可能的话,我希望使用纯JavaScript。


共1个答案

匿名用户

null

function check(config) {
    // config.background
    // config.color
    // config.font
}

check({ background: 'red', color: 'blue', font: 'arial' });

如果您需要或希望函数也支持用常规参数调用,则始终可以检测参数类型:

function check(background, color, font) {
    if(typeof background === 'object') {
        color = background.color;
        font = background.font;
        background = background.background;
    }
    // background, color, and font are what you expect
}

// you can call it either way:
check('red', 'blue', 'arial');
check({ background: 'red', color: 'blue', font: 'arial' });

最后,如果您不想(或者不知何故不能)修改原始函数,可以将其包装起来:

var originalCheck = check;
check = function(config) {
    originalCheck(config.background, config.color, config.font);
}