JS:如何将值存储在循环中的数组中(每个)并进行比较

JS: How to store values in an array in a loop(each) and compare this?

本文关键字:每个 数组 比较 JS 存储 循环      更新时间:2023-09-26

我正在开发一个小插件,用于检查两个输入是否具有相同的值。我认为最好的方法是将值存储在数组中,并检查这些值是否唯一,或者有更好的方法吗?

//的想法

$('input').each(function(){
   var type = $(this).attr('class');//can be a other attribute
   switch(type){
      case: 'red':
      // some code
      break;
      case: 'green':
      // some code
      break;
      case: 'black':
      // the code to see if all inputs with the class black 
      //if they have the same value return in true or false, if all of the values
      // are empty it should return false
      break;
      // more cases....
   };
});

我会为它使用一个对象:

var values = {};
var dupFound = false;
$(...).each(function() {
    var value = $(this).val();
    if(values[value]) {
        dupFound = true;
    }
    else {
        values[value] = this;
    }
});

这样做的优点是可以轻松访问包含该值的其他元素。

function checkMatchingValues(cssClass) {
    var value, matching = true;
    $('input#' + cssClass).each(function() {
        if(value == undefined) {value = this.val(); return}
        if(value != this.var()) {matching = false; return}
    }
    return matching;
}