检查js函数的所有参数是否为非空,最有效/最常见的方法是什么
What is the most efficient/common way to check if all parameters of a js function is non-empty?
例如,我有一个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/
相关文章:
- 如何有效地将游戏数据存储在URL查询字符串中
- 如何使用Node.js最有效地解析网页
- jquery代码在Mozilla中有效,但在其他浏览器上无效
- 有效形式-始终只显示1个错误[角度]
- Javascript袖珍参考,第121页:这是怎么回事;猴子补丁”;方法应该有效
- 单击仅在第二次单击后有效
- 什么'是在asp.net MVC中将本地化的resources.resx文件转换为javascript文件的有效
- 为什么自我执行匿名有效
- D3.js生成有效的SVG,但不显示任何内容
- 如何在AngularJS中有效地检查日期是否有效
- 捕获所有常见类型的重定向、头、元、JavaScript等
- 为什么不是'我的函数在解析云代码中工作吗?当我在Angular和Express中测试时,它是有效的
- 滚动在Chrome中有效,但在Firefox或IE中无效
- 有效地获取两个区间之间的随机整数
- Rails将JavaScript对象存储到Model的有效方式
- 在UI路由器中以抽象状态填充常见视图
- Javascript XMLHttpRequest——只有第一个POST请求有效
- 使用条件语句,使 jquery fadeIn/fadeOut 仅在视口 >= 480px 时才有效
- 在Backbone.JS中一次性获取有效负载和元数据的常见方法
- 检查js函数的所有参数是否为非空,最有效/最常见的方法是什么