如何以这种方式比较3个值?

时间:2018-09-05 13:20:30

标签: javascript

我需要一种以如下方式比较3个值的方法:

'aaa'=='aaa'=='aaa'
false

但是如您所见,它不起作用。为什么?

具有2个值的确可以正常工作:

'aaa'=='aaa'
true

5 个答案:

答案 0 :(得分:4)

比较前两个值将得出true,然后将true"aaa"进行比较,得出false

要使其正确,您可以编写:

const a = 'aaa';
const b = 'aaa';
const c = 'aaa';

console.log(a === b && b === c); //true

答案 1 :(得分:2)

如果您将这些字符串存储在变量中,则可以

let a = 'aaa', b = 'aaa', c = 'aaa'

console.log(a === b && b === c) // true

答案 2 :(得分:1)

表达式OAUTH 2被计算为'aaa'=='aaa'=='aaa'

括号中的子表达式的值为('aaa'=='aaa')=='aaa',它变为true的{​​{1}},因为在比较两个不同类型的值时,JavaScript首先为converts one of them or both to a common type。它将布尔值true=='aaa'转换为数字false,并将字符串true转换为数字1,这显然是不相等的。

您需要的是

'aaa'

答案 3 :(得分:0)

您可以将所有值放入Array中,然后使用Array.prototype.every()函数测试所有值是否都满足传递给它的回调中定义的条件:

let a = 'aaa', b = 'aaa', c = 'aaa'

let arr = [a, b, c]

let arr2 = [1, 2, 1]

console.log(arr.every(i => [arr[0]].includes(i)))
console.log(arr2.every(i => [arr2[0]].includes(i)))

答案 4 :(得分:0)

此外,您可能会从给定的序列中获得唯一值,并且如果获得单个元素,则是因为它们都相等:

public void onTick(long millisUntilFinished) {
      if (isCanceled) {
          cancel();
          buttonsVisibility();
          //isCanceled = false;   //comment or delete this line               
      }else{
          int minutes = (int) (millisUntilFinished / 1000) / 60;
          int seconds = (int) (millisUntilFinished / 1000) % 60;
          countDownTextView.setText("Time left: " + String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds));
          mBuilder.setContentText("Time left: " + String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds));
          notificationManager.notify(3, mBuilder.build()); //only notify when isCanceled is false
      }                    
}

带有可变参数

const same = xs => new Set (xs).size === 1

const x = 'aaa'
const y = 'aaa'
const z = 'aaa'

const areSame = same ([ x, y, z ])

console.log(areSame)

const x_ = 'aaa'
const y_ = 'bbb'
const z_ = 'aaa'

const areSame_ = same ([ x_, y_, z_ ])

console.log (areSame_)