triple equals gives wrong output when strings are compared, but in case of integer it gives correct output

霸气de小男生 提交于 2019-12-24 20:12:20

问题


I have an array of string like

var a = ['a','a','a'];

When I do comparison like a[0]==a[1]==a[2] it gives me result as false but when I change the value of array to ['1','1','1'] and do the same comparison like above the result will betrue.

Again when I change the input to ['9','9','9'] then above comparison is giving me result as false.

Can anybody tell me the reason behind this behaviour in javascript ?


回答1:


What you need is

a[0]==a[1] && a[0]==a[2]

In your case, when you are comparing ['1','1','1'], what happening is

a[0] == a[1]  // true
true == a[2]  // true as true == '1'



回答2:


What happens is that it executes it like this:

 ((a[0]==a[1])==a[2]):

1.

(a[0] == a[1]) => true

2.

(true == a[2]) => false

Because: 1 == true, the array [1,1,1] returns true




回答3:


It's easier to understand if you test the inner value direct: 0==0==0 is understood as (0==0)==0, so 0==0 is true, what's tested next is (true)==0, 0 is interpreted as false, and true==false is false.

For the other comparisons the first part is the same, but 1 or 9 are interpreted as true.




回答4:


This is expected output

// Case 1
var a = ['a','a','a'];

The output of 

a[0] == a[1] --> true

Next Comparison

true == a[2] --> false // true != 'a';

// Case 2

var a = ['1','1','1'] ;

a[0] == a[1] --> true

true == a[2] --> true // true == "1"

However, in case 2 if you use strict equality operator then the result will be false.

var a = ['1','1','1'] ;

// strict equality operator
console.log(a[0]===a[1]===a[2]);

// without strict equality operator
console.log(a[0]==a[1]==a[2]);



回答5:


If you see the associativity of operator == it is left-to-right. So in your case

when var a = ['a','a','a']; a[0]==a[1]==a[2] this evaluate a[0]==a[1] first then result of this with a[3] means true == 'a' which returns false.

In case when var a = ['1','1','1']; so as per associativity this evaluates from left to right in expression a[0]==a[1]==a[2] results '1' == '1' in first, then true == '1' in second which gives true finally.

In case when var a = ['9','9','9']; first '9' == '9' then true == '9' which finally evaluates to false. Hope this helps.



来源:https://stackoverflow.com/questions/56770800/triple-equals-gives-wrong-output-when-strings-are-compared-but-in-case-of-integ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!