简体   繁体   English

javascript中的单引号和双引号值比较 - 严格类型

[英]single quote and double quote value comparison in javascript - Strict type

From the below code when I want to compare variable y and z, here strict type of comparison is matching, but y==z is not matching.当我想比较变量 y 和 z 时,从下面的代码中,这里严格的比较类型是匹配的,但 y==z 不匹配。 Can anybody explain the reason and how strict type works ?任何人都可以解释原因以及严格类型的工作原理吗?

<script language="javascript" type="text/javascript">
    var x=11;
    var y="11";
    var z='11';

    if(x==y)
        alert('x==y');
    if(y==z)
        alert('y==z');
    if(x===y)
        alert('x===y');
    if(y===z)
        alert('y===z');
    if(x==z)
        alert('x==z');
    if(x===z)
        alert('x===z');
</script>

Both are string and also it's matching.两者都是字符串,也是匹配的。

> typeof "11";
"string"
> typeof '11';
"string"
> "11" === '11'
true
> "11" == '11'
true

JavaScript has both strict and type-converting equality comparison. JavaScript 有严格的和类型转换的相等比较。 For strict equality the objects being compared must have the same type and:对于严格相等,被比较的对象必须具有相同的类型,并且:

Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.当两个字符串具有相同的字符序列、相同的长度并且在相应位置具有相同的字符时,它们是严格相等的。 Two numbers are strictly equal when they are numerically equal (have the same number value).当两个数字在数值上相等(具有相同的数值)时,它们是严格相等的。 NaN is not equal to anything, including NaN. NaN 不等于任何东西,包括 NaN。 Positive and negative zeros are equal to one another.正零和负零彼此相等。 Two Boolean operands are strictly equal if both are true or both are false.如果两个布尔操作数都为真或都为假,则两个布尔操作数严格相等。 Two objects are strictly equal if they refer to the same Object.如果两个对象引用同一个对象,则它们严格相等。 Null and Undefined types are == (but not ===). Null 和 Undefined 类型是 ==(但不是 ===)。 [Ie (Null==Undefined) is true but (Null===Undefined) is false] [即 (Null==Undefined) 为真但 (Null===Undefined) 为假]

Check this out 看一下这个

When you use double equals ( Loose equality ) you only compare values , but when using three equals ( Strict equality ) you compare types too.当您使用双相等(松散相等)时,您只比较,但是当使用三个相等(严格相等)时,您也比较类型

Loose equality compares two values for equality, after converting both values to a common type.松散相等比较两个值是否相等,然后将两个值转换为公共类型。

So, if因此,如果

var y = 11; // number
var z = '11'; // string

var equalValues = y == z; // true
var equalValuesAndTypes = y === z; // false

You can check the MDN docs您可以查看MDN 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM