Javascript compare 3 values

后端 未结 7 2390
执笔经年
执笔经年 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!
    }
    

提交回复
热议问题