admin管理员组

文章数量:1315310

Is it possible to check if all variables are different from each other in another way than this?

var a = 1, b = 2, c = 3, d = 4;

if(a != b && a != c && a != d && b != a && b != c && b != d && c != a && c != b && c != d && d != a && d != b && d != c){
  //All numbers are different
}

for example

if(a != b != c != d){

}

Is it possible to check if all variables are different from each other in another way than this?

var a = 1, b = 2, c = 3, d = 4;

if(a != b && a != c && a != d && b != a && b != c && b != d && c != a && c != b && c != d && d != a && d != b && d != c){
  //All numbers are different
}

for example

if(a != b != c != d){

}
Share Improve this question edited May 28, 2015 at 9:47 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked May 28, 2015 at 9:26 gr3ggr3g 2,9145 gold badges31 silver badges52 bronze badges 2
  • Normally, this questions arises when your data are structured (an array, an object, etc.). The first step here is probably to have a proper design for your data. – Denys Séguret Commented May 28, 2015 at 9:27
  • I'd advise you to make an array of the variables and loop through them! If you really want to stay with the major if case, You could go for some if else if construction. – qLuke Commented May 28, 2015 at 9:29
Add a ment  | 

7 Answers 7

Reset to default 6

You can store them all in an object and check if the number of keys is equal to the number of variables used, like this

var dummy = {};
dummy[a] = true;
dummy[b] = true;
dummy[c] = true;
dummy[d] = true;
console.log(Object.keys(dummy).length === 4);

If the values are different, then a new key will be created every time and the number of keys will be equal to the number of variables used.

As Denys Séguret mented, if you have a proper structure for your data then it will be possible to do it in a more elegant way.

However, with what you have you can still simplify as you can remove duplicate checks.

For example, you check that a != b and then later that b != a. Those two checks are effectively the same, just in a different order.

Removing all duplicates gives you...

if(a != b && a != c && a != d && b != c && b != d && c != d)

Which is somewhat simpler, although you'd still be better off structuring your data.

Another solution is to push the variables in an array:

var a = 1,
  b = 2,
  c = 3,
  d = 4;

var arr = [];
arr.push(a);
arr.push(b);
arr.push(c);
arr.push(d);
var sorted_arr = arr.sort(); // You can define the paring function here. 
// JS by default uses a crappy string pare.
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
  if (sorted_arr[i + 1] == sorted_arr[i]) {
    results.push(sorted_arr[i]);
  }
}

alert(results);

Another way using arrays

var a =10, b = 20, c=30, d =40, e =50;
alert(isVariablesDifferent(a,b,c,d,e));

function isVariablesDifferent(){
    var params = Array.prototype.slice.call(arguments);
    for(var i = 0; i < params.length; i++){
        if(params.lastIndexOf(params[i]) !== i){
            return false;
        }
    }
    return true;
}

I made a function for testing this for you. This could be costly with large data sets though.

Here is the fiddle: https://jsfiddle/Luqm8z7b/

function uniqueTest(ary){
 for(var i=ary.pop(); ary.length > 0;i=ary.pop()){
  for(var j = 0; j < ary.length; j++){
   if(i === j) return false;
  }
 }
 return true;
}

var a = 1, b = 2, c = 3, d = 4;
var list = [];
list.push(a, b, c, d);
console.log(uniqueTest(list));

Make an array of the variable. Iterate the entire from first to last element and pare or otherwise hardcode like below.

var a = 1, b = 2, c = 3, d = 4; 

if(a != b && a != c && a != d && b != c && b != d && c != d)
alert('all the variables are unique');

Kindly refer my sample code in jsfiddle

http://jsfiddle/parthipans/fNPvf/15217/

I believe that without context it should be hard to provide a quality answer, but since ECMA-Script 5 there's an Array.prototype.every function to check if all array items do conform a boolean expression. That is, you can express the same problem this way:

var a = 1, b = 2, c = 3, d = 4; 

if(
  [b, c, d].every(function(someVar) { return someVar != a; })
  && [a, c, d].every(function(someVar) { return someVar != b })
  && [a, b, d].every(function(someVar) { return someVar != c })
  && [a, b, c].every(function(someVar) { return someVar != d })
) {
  alert("all different!");
}

Or check how you can even simplify this implementing a different(...) function to Array.prototype (or you can implement it as a property of some custom object or as just a regular procedural function...).

Array.prototype.different = function() {
  var results = [];
  
  for(var i = 0; i < this.length; i++) {
     // This is to clone the array so we don't modify the source one
     var arrayCopy = [].concat(this);
    
     // This drops the variable value to check and returns it
     var varValueToCheck = arrayCopy.splice(i, 1);
    
     // Then we use every to check that every variable value doesn't
     // equal current variable value to pare
     results.push(arrayCopy.every(
       function(varValue) {
         return varValue != varValueToCheck;
       })
     );
  }
  
  // Once we've got all boolean results, we call every() on
  // boolean results array to check that all items are TRUE
  // (i.e. no variable equals to other ones!)
  return results.every(function(result) { return result; });
};

// This should avoid that other libs could re-define "different"
// function, and also it should avoid for..in or forEach issues
// finding unexpected functions, as this function will be hidden 
// when iterating Array.prototype
Object.defineProperty(Array.prototype, "different", {
  enumerable: false,
  configurable: false,
  writable: false
});

var a = 1, b = 2, c = 3, d = 4; 

// Simplified check! 
if([a, b, c, d].different()) {
   alert("also all different!!!");  
}

Now the issue might be if simplifying an if statement like yours with something like my proposal is an overkill or not, but this will depend on your actual use case.

本文标签: javascriptHow can I check if all variables are differentStack Overflow