检查多个参数是否不是""用循环JS或jQuery

时间:2017-01-01 12:42:58

标签: javascript jquery

我想创建一个可以取n1,n2,n ......,n = params数的函数。 我知道有使用arguments[0]对象来选择参数的事情。是否可以遍历所有传递的参数并检查它们的值! = ""

function test () {
    loop through arguments[] object 
    IF arguments[index] == "" return false 
};

test("ok","", "no");将返回false

test("ok");将返回true

目标是即使没有一定数量的参数,该功能也能正常工作。

Javascript和jQuery答案都欢迎。

PS:如果有可能,有限制吗?可能的问题。

2 个答案:

答案 0 :(得分:3)

使用Array.prototype.slice()Array.prototype.some()函数缩短 ECMAScript5 解决方案:



function checkFilling() {
  return !Array.prototype.slice.call(arguments).some(function (arg) {
      return arg === "";
  });
}
    
console.log(checkFilling("ok","", "no"));
console.log(checkFilling("ok"));




使用Array.from()函数的替代 ECMAScript6 方法(从类似数组的arguments对象创建新数组):



function checkFilling() {
    return !Array.from(arguments).some(arg => arg === "");
}

console.log(checkFilling("ok","", "no"));
console.log(checkFilling("ok"));



  

答案 1 :(得分:0)

本着精神回答这个问题的问题代码适用于所有浏览器,并且初学者也可以理解和理解

function test() {
  for (var i=0,n=arguments.length;i<n; i++) {
    // return false if any argument is strictly equal to the empty string
    if (arguments[i]==="") return false; 
  }  
  return true;
}

// Tests

console.log(test(""),false)
console.log(test("1"),true)
console.log(test(1),true)
console.log(test("1",""),false)
console.log(test("1","2"),true)