为什么string =' 0'并不严格等于javascript中的新字符串(' 0')

时间:2017-07-11 13:34:45

标签: javascript

为什么在严格比较原始字符串值时,字符串对象的创建不会返回true?

var obj = new String('0');
var str = '0';

console.log(obj == str); //returns true
console.log(obj === str); //returns false

3 个答案:

答案 0 :(得分:9)

由于obj类型为object,其中strstring,因此obj === strfalse

var obj = new String('0');
var str = '0';

console.log(typeof obj);
console.log(typeof str);

答案 1 :(得分:0)

console.log(obj == str); //returns true
console.log(obj === str); //returns false

Identity and equals operators is quite different things. Second case is very simple, because object can't be identical to string. First case evolves boxing/unboxing mechanism, and result value is dependent on operator in expression. In this example, because str is primitive, obj will be unboxed, and comparation will success.

Expression new String('xxx') == new String('xxx') , of course, will be false, because there is no primitive value to force convert to it's type. See https://www.w3schools.com/js/js_type_conversion.asp获取相同的显示以获取详细信息。

答案 2 :(得分:0)

String ObjectString type value不一样,这就是为什么' ==='给出false

如果要创建字符串对象,则它与字符串类型值不同。

var obj = new String('0'); // this is object type
var str = '0';             // this is string type value

当你使用' ==='这是严格的平等,

  

严格相等性比较两个相等的值。在比较之前,这两个值都不会隐式转换为其他值。如果值具有不同的类型,则认为这些值不相等。   Read More

这就是为什么当您使用' ==='(严格比较)时,它会返回false

检查此答案以查看字符串对象与字符串类型值Difference between the javascript String Type and String Object

之间的区别
相关问题