Javascript JS:如何将数组中的值存储在循环中(每个循环)并进行比较?
我正在开发一个小插件,它可以检查两个输入是否具有相同的值。我认为最好的方法是将值存储在数组中,并检查值是否唯一,或者有更好的方法吗 //想法Javascript JS:如何将数组中的值存储在循环中(每个循环)并进行比较?,javascript,jquery,arrays,loops,match,Javascript,Jquery,Arrays,Loops,Match,我正在开发一个小插件,它可以检查两个输入是否具有相同的值。我认为最好的方法是将值存储在数组中,并检查值是否唯一,或者有更好的方法吗 //想法 $('input').each(function(){ var type = $(this).attr('class');//can be a other attribute switch(type){ case: 'red': // some code break; case: 'green'
$('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;
}
});
这样做的好处是,您可以轻松访问包含该值的其他元素。如果要检查输入的值,为什么代码要查看“class”属性?哦,等等;您想按类检查类似的值。。。这将是一件非常脆弱的事情,因为一个元素可以有多个“类”值;或者,更恰当地说,“类”在语义上是一个值列表。“返回真-假”是什么意思?这些输入可以返回什么数据类型?还有-为什么要将类存储在数组中?难道你不想知道它们是否都相同吗?只需将first的元素类分配给一个变量,并将其与其他变量进行比较..,该类只是一个想法,我将使用html5数据属性。false中true的返回是,如果所有值都相同,则应返回true,否则返回false。数据类型?不,我不想存储类,而是存储具有相同类的输入值。
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;
}