字符串相同如何在JavaScript中工作? [英] How does string equality work in JavaScript?

查看:173
本文介绍了字符串相同如何在JavaScript中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

== === 有很多教程,所以请不要指导我基本教程,我的问题更具体一点:

There are plenty of tutorials for == and === so please don't guide me to a basic tutorial, my question is a bit more specific:

例如 http://www.w3schools.com/jsref/jsref_obj_string.asp 声明:

语法:

var txt = new String("string");

// or more simply:
var txt = "string";

很好,但是这个怎么样?

Good, but what about this?

alert(new String("a") == new String("a")); // false
alert("a" == "a"); // true

var a = new String("a");
var b = new String("a");
alert(a == b); // false

var c = "a";
var d = "a";
alert(c == d); // true

alert(c === d); // true
alert (a === c); // false

当然没有人调用 new String()无论如何,但它是关于相等失败的事情,因为 new String()被处理为一个对象而不是一个字符串?

Of course nobody calls new String() anyway, but is it something about the equality failing because new String() is handled as an object not as a string?

当然,W3Schools并不是最值得信赖的来源,但我希望上述所有提醒都能说明。

And of course W3Schools is not the most trusted source but I would have expected all of the above alerts to say true.

请解释。

推荐答案

令人惊讶的结果来自于Javascript处理对象的相等性,以及字符串文字和String对象之间出现的混淆。来自Mozilla 参考指南 == 运算符:

The "surprising results" come from the way Javascript handles equality for Objects, plus the confusion that arises between string literals and String objects. From the Mozilla reference guide for the == operator:


如果两个操作数的类型不同,JavaScript会转换
个操作数然后应用严格的比较。如果任一操作数是数字
或布尔值,则操作数将转换为数字(如果可能); else
如果任一操作数是字符串,则另一个操作数转换为
字符串(如果可能)。 如果两个操作数都是对象,则JavaScript
比较内部引用,当操作数引用
内存中的同一对象
时,内部引用相等。

您可以通过数字体验相同的行为:

You can experience the same behavior with numbers:

new Number(5) == new Number(5) // false

并通过以下方式澄清您的想法:

And clarify your mind by:

typeof "string" // string
typeof new String("string") // object

这篇关于字符串相同如何在JavaScript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆