0

我想遍历一组字符串,看看它们是否都彼此相同。如果循环的所有字符串都相同,我想运行一个函数。如果不是,请运行另一个函数。

$(".variationPrice").each(function(){
    var price = $(this).text();
        if(price == price){
             allMatch();
        } else{
             notMatch();
        }
});

换句话说,如果我们有以下数据,它将运行allMatch():$55, $55, $55

如果我们有以下数据,它将运行noMatch():$55, $45, $55

上面的代码不起作用,但作为一个起点。在上面的代码中,价格总是匹配价格。我需要想办法将第一个价格存储在一个变量中,并将之后的所有结果与初始价格进行比较。通过 jquery / javascript 比较字符串的好方法是什么?

更新 一个想法是将所有内容推入一个数组,然后查看数组中是否有重复项,如下所示:

var array1=[2,2,1,2,2,2];
function checkForDuplicates(arr){
var x = arr[0];
for(var i=1;i<arr.length;i++){
    if(x!=arr[i]){return 'at least one duplicate found'}
    }
return 'no duplicates found';
}
4

1 回答 1

1

使用您的初始代码,您只需要一些可从 each() 范围之外获得的变量。这段代码应该可以解决问题。

var allMatch = true;
var price;
$(".variationPrice").each(function(){
    if (price === undefined) {
        price = $(this).text();
    }
    if (price != $(this).text()){
        allMatch = false;
        return false; // No need to check the rest of the array..
    }
});

if (allMatch) {
    allMatch();
} else {
    notMatch();
}

根据评论的建议进行了优化。

于 2013-08-18T23:44:16.807 回答