将唯一的JQuery对象推送到数组 [英] Pushing Unique JQuery Objects to an Array

查看:59
本文介绍了将唯一的JQuery对象推送到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用Jquery完全不熟悉,我正在尝试将唯一对象推送到数组,如果对象已经在数组中,则会删除它们。这是为了让学生通过单击可用选项预订多个教程类,然后提交包含所有选定选项的完整数组。



我已完全更新了我的代码我写的是什么如果我只使用数组中的单个元素,此代码可以正常工作。如果我在数组中使用对象,则无法评估重复的选定插槽。

  var bookingSlots = []; 
$('。row')。on('click','。slots',function(e){
e.preventDefault();
$(this).toggleClass('选择');
var slotID = $(this).attr('data-slot-id');
var studentID = $(this).attr('data-student-id');
var slot = {slotID:slotID,studentID:studentID};
var found = jQuery.inArray(slot,bookingSlots);

if(found< 0){
bookingSlots.push(slot);
} else {
bookingSlots.splice(found,1);
}
});


解决方案

来自您的评论:


每次点击都会创建对象


这就是问题所在:等价对象彼此不是 == === ,而 inArray 使用 === 查找对象。例如, $。inArray({id:1},[{id:1}])返回 -1



  console.log($。inArray({id:1},[{id:1}] )); // -1  

 < script src =https: //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>  



所以你想要使用别的东西。在现代浏览器中,您可以使用 Array#findIndex 并使用谓词函数:

  var index = array.findIndex(function(e){return e.id == id&& e.id2 == id2;}); 

示例:



  var array = []; run(1,1); // addsrun(1,2); // addsrun(1,1); // removedconsole.log(array); //最后只有itfunction中的1,2对象运行(id,id2){//如果有任何var index = array.findIndex,则查找等效对象(function(e){return e.id == id&& ; e.id2 == id2;}); //找到了? if(index == -1){//不,添加一个array.push({id:id,id2:id2}); } else {//是的,删除它array.splice(index,1); }  



数组#findIndex 可以在旧浏览器上进行填充/填充; MDN有一个polyfill 这里 (我也在下面引用它,以防万一,但我无法想象MDN会很快消失)






附注:ES2015(又称ES6)更简洁(浏览器尚未准备好让我们在野外使用ES2015,但你可以透露):

  let index = array.findIndex(e => e.id == id&& e.id2 == id2); 






在撰写本文时,这是MDN的polyfill(25 / 05/2016):

  if(!Array.prototype.findIndex){
Array.prototype.findIndex = function (谓词){
if(this === null){
抛出新的TypeError('调用null或undefined'的Array.prototype.findIndex);
}
if(typeof predicate!=='function'){
抛出新的TypeError('谓词必须是函数');
}
var list = Object(this);
var length = list.length>>> 0;
var thisArg = arguments [1];
var value;

for(var i = 0; i< length; i ++){
value = list [i];
if(predicate.call(thisArg,value,i,list)){
return i;
}
}
返回-1;
};
}


I'm completely new to using Jquery, and I'm trying push unique objects to an array, and if the object is already in the array, it removes them. This is for students to book multiple tutorial classes by clicking on available options, and then submitting the full array with all their selected options.

I've updated my code exactly from what I've written. This code works perfectly if I just use single elements in the array. It cannot evaluate duplicate selected slots if I use objects in the array.

   var bookingSlots = [];
   $('.row').on('click','.slots', function (e) {
    e.preventDefault();
    $(this).toggleClass('selected');
    var slotID = $(this).attr('data-slot-id');
    var studentID = $(this).attr('data-student-id');
    var slot = {slotID: slotID, studentID: studentID};
    var found = jQuery.inArray(slot,bookingSlots);

    if(found < 0){
        bookingSlots.push(slot);
    }else{
        bookingSlots.splice(found, 1);
    }
});

解决方案

From your comment:

the object is being created on every single click

That's the problem: Equivalent objects are not either == or === to each other, and inArray uses === to find the object. For instance, $.inArray({id:1}, [{id:1}]) returns -1:

console.log($.inArray({id:1}, [{id:1}])); // -1

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

So you'll want to use something else. On modern browsers, you can use Array#findIndex and use a predicate function:

var index = array.findIndex(function(e) { return e.id == id && e.id2 == id2; });

Example:

var array = [];
run(1, 1); // adds
run(1, 2); // adds
run(1, 1); // removes
console.log(array); // ends up with just the 1,2 object in it

function run(id, id2) {
  // Find the equivalent object if any
  var index = array.findIndex(function(e) { return e.id == id && e.id2 == id2; });
  
  // Found?
  if (index == -1) {
    // No, add one
    array.push({id: id, id2: id2});
  } else {
    // Yes, remove it
    array.splice(index, 1);
  }
}

Array#findIndex can be shimmed/polyfilled on older browsers; MDN has a polyfill here (I've also quoted it below, just in case, but I can't imagine MDN disappearing any time soon).


Side note: It's a bit more concise with ES2015 (aka "ES6") (browsers aren't quite ready for us to use ES2015 in the wild yet, but you can transpile):

let index = array.findIndex(e => e.id == id && e.id2 == id2);


Here's MDN's polyfill as of this writing (25/05/2016):

if (!Array.prototype.findIndex) {
  Array.prototype.findIndex = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.findIndex called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return i;
      }
    }
    return -1;
  };
}

这篇关于将唯一的JQuery对象推送到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆