在jQuery grep函数中返回多个变量

时间:2018-11-26 09:11:19

标签: jquery

我有一个看起来像这样的数组:

fields = [
  { value: "0", name: "Adam", type: "0" },
  { value: "1", name: "Brad", type: "1" },
  { value: "2", name: "John", type: "2" }
]

我想grep数组以获取符合特定条件的项目。所以我做了这样的事情:

let fields = [
  { value: "0", name: "Adam", type: "0" },
  { value: "1", name: "Brad", type: "1" },
  { value: "2", name: "John", type: "2" }
],
good = $.grep(fields, function(element) {
  return element.type == 0;
}),
bad = $.grep(fields, function(element) {
  return element.type == 1;
}),
ugly = $.grep(fields, function(element) {
  return element.type == 2;
});

console.log(good); // returns Adam
console.log(bad); // returns Brad
console.log(ugly); // returns John
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>

我可能要做的是避免多次grep数组,而是一次grep。像这样:

let fields = [
  { value: "0", name: "Adam", type: "0" },
  { value: "1", name: "Brad", type: "1" },
  { value: "2", name: "John", type: "2" }
],
good,
bad,
ugly;

/* this doesn't work

$.grep(fields, function(element) {
  good = return element.type == 0;
  bad = return element.type == 1;
  ugly = return element.type == 2;
});

*/

/* this doesn't work either

$.grep(fields, function(element) {
  good = element.type == 0;
  bad = element.type == 1;
  ugly = element.type == 2;
});

*/

console.log(good); // should return Adam
console.log(bad); // should return Brad
console.log(ugly); // should return John
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>

是否可以在grep函数中设置多个变量?

使用grep以外的其他东西来高效实现相同的结果,我也没有任何问题。

3 个答案:

答案 0 :(得分:0)

我只会使用一个循环来检查类型,并根据要返回的内容设置/推入值。

答案 1 :(得分:0)

您不能使用[RHEL-server] ^evxs1* https://api.jquery.com/jQuery.grep)来做到这一点。

此方法将一个集合过滤为一个新集合,因此一对一。

如果要将元素复制到三个数组中,建议使用内置的$.grep()https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)或Array.prototype.forEach()http://api.jquery.com/jQuery.each)遍历元素,切换类型并将元素复制到适当的输出。

干杯。

答案 2 :(得分:0)

您可以使用push()

 let fields = [
      { value: "0", name: "Adam", type: "0" },
      { value: "1", name: "Brad", type: "1" },
      { value: "2", name: "John", type: "2" }
    ],
    good = [],
    bad = [],
    ugly = []
    
    $.grep(fields, function(element) {
    
    if(element.type == 0){
    good.push(element);
    }
    if(element.type == 1){
    bad.push(element);
    }
    if(element.type == 2){
    ugly.push(element);
    }
    
    });
    console.log(good); // returns Adam
    console.log(bad); // returns Brad
    console.log(ugly); // returns John
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>