Javascript compare 3 values

后端 未结 7 2370
执笔经年
执笔经年 2020-11-29 11:04

I have 3 values that I want to compare f, g and h. I have some code to check that they all equal each other and that none of them are null. I\'ve had a look online but could

相关标签:
7条回答
  • 2020-11-29 11:28

    Add a distinct function to Array.prototype:

    Array.prototype.distinct = function() {
        var result = [];
        for(var i = 0; i < this.length; i++) {
            if (result.indexOf(this[i]) == -1) {
                result.push(this[i]);
            }
        }
        return result; 
    }
    

    Then do:

    var myArray = [f, g, h];
    if (myArray.indexOf(null) == -1 && myArray.unique().length == 1)
    {
        // no nulls and all elements have the same value!
    }
    
    0 讨论(0)
  • 2020-11-29 11:28

    Create an array of string and check the existance of next value in there

    compareAnswers(a1: string, a2: string, a3: string): boolean {
       this.compareAnswerArr.push(a1);
    if (this.compareAnswerArr.includes(a2) == false) {
      this.compareAnswerArr.push(a2);
      if (this.compareAnswerArr.includes(a3) == false) {
        return true;
      } else return false;
    }
    else return false;}
    
    0 讨论(0)
  • 2020-11-29 11:39

    You could shorten that to

    if(g === h && g === f && g !== null)
    {
    //do something
    }
    

    For an actual way to compare multiple values (regardless of their number)
    (inspired by/ simplified @Rohan Prabhu answer)

    function areEqual(){
       var len = arguments.length;
       for (var i = 1; i< len; i++){
          if (arguments[i] === null || arguments[i] !== arguments[i-1])
             return false;
       }
       return true;
    }
    

    and call this with

    if( areEqual(a,b,c,d,e,f,g,h) )
    {
    //do something
    }
    
    0 讨论(0)
  • 2020-11-29 11:39

    I suggest you write a function where you give an array with all the values you want to compare and then iterate through the array to compare the values which each other:

    function compareAllValues(a) {
         for (var i = 0; i < a.length; i++) {
             if (a[i] === null) { return false }
             for (var j = 0; j < i; j++) {
                if (a[j] !== a[i]) { return false }
             }
         }
    
         return true;
    }
    

    that should be it, I think :)

    0 讨论(0)
  • 2020-11-29 11:43

    Works for any number of items.

    ES5

    if ([f, g, h].every(function (v, i, a) {
      return (
        v === a[0] &&
        v !== null
      );
    })) {
      // Do something
    }
    

    ES2015

    if ([f, g, h].every((v, i, a) => 
      v === a[0] &&
      v !== null
    )) {
      // Do something
    }
    
    0 讨论(0)
  • 2020-11-29 11:49

    What about

    (new Set([a,b,c])).size === 1
    
    0 讨论(0)
提交回复
热议问题