检查js函数的所有参数是否为非空,最有效/最常见的方法是什么

What is the most efficient/common way to check if all parameters of a js function is non-empty?

本文关键字:有效 常见 是什么 方法 函数 js 参数 检查 是否      更新时间:2023-09-26

例如,我有一个js函数,如下所示:

function test(param1, param2, param3, ..., param10)
{
   //do something inside
}

检查这十个参数是否全部为非空的最有效/最常见的方法是什么(此处为空表示NULL或空字符串。注意:此处不认为0为空!(。以下方法是最好的方法吗?

function test(param1, param2, param3, ..., param10)
{
   if(param1==="" || param2==="" || ... || param10==="") )
   {
       //some parameters are empty string and should return false
   }
}

如果有完全相同的问题,请把这个标记为重复。谢谢

我相信这就是您的要求。使用Array.prototype.every,也就是ES5,但如果需要支持较旧的浏览器,可以使用for循环。

var pre = document.getElementById('out');
                                  
function log(str) {
    pre.textContent += str + ''n';
}
function argCheck(arg) {
    return arg !== null && arg !== '';
}
function test() {
    if (Array.prototype.every.call(arguments, argCheck)) {
        log('ok');
    } else {
        log('not ok');
    }
}
test();
test(0);
test('');
test(undefined);
test(null);
test(1, 2, 3, 4, 5, 6);
test(1, 2, 3, '', 5, 6);
test(1, 2, 3, null, 5, 6);
<pre id="out"></pre>

如果你需要检查是否也提供了一定数量的参数,那么添加一个检查

arguments.length === X

如果你想检查参数是否为true,那么你可以进行

Array.prototype.every.call(arguments, Boolean)

当然,如果你没有太多的参数要检查,也就是说你只有一个,那么最(代码(有效的方法就是只测试那一个参数。

function test(arg1) {
    if (arg1 !== null && arg1 !== '') {
        log('ok');
    } else {
        log('not ok');
    }
}

类似的东西可以工作:

function test(param1, param2)
{
   for (i=0; i<arguments.length; i++)
       if (arguments[i] === ""){
        console.log("empty" + i);   
       }
}
test("not empty", "");

http://jsfiddle.net/6tbnzjsu/

这里有另一个使用过滤方法的想法:

function test(param1, param2, param3, param4) {
    var notEmpty = [param1, param2, param3, param4];
    console.log(notEmpty);
    var filtered = notEmpty.filter(check);
    console.log(filtered);// Only first paramater will be returned "not empty", rest is filtered out
}
//filter function
function check(value) {
    return value !== "" && value !== null && value !== 0;
}
//call test function 
test("not empty", "", 0, null);

还有小提琴http://jsfiddle.net/6tbnzjsu/2/