javascript difference between == and ===

本文详细介绍了JavaScript中严格的和类型转换的相等性比较。包括字符串、数值、布尔值及对象之间的比较规则,并通过实例展示了如何进行相等性判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JavaScript has both strict and type-converting equality comparison. 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. 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 ===).

  • 0==false   // true
    0===false  // false, because they are of a different type
    1=="1"     // true, auto type coersion
    1==="1"    // false, because they are of a different type
  • >>> new String("aa")===new String("aa")
    false
    >>> new String("aa")==new String("aa")
    false
  • >>> "aa"=="aa"
    true
    >>> "aa"==="aa"
    true
  • >>> NaN===NaN //false

  • >>> var user1 = {name : "nerd", org: "dev"}; var user2 = {name : "nerd", org: "dev"}; console.log(user1==user2)
    false
     
       
      For furthur information, please check
  • http://stackoverflow.com/questions/1068834/object-comparison-in-javascript
04-01
### Comparison Operator Usage and Meaning In programming languages, the `==` operator is a **comparison operator** used to check whether two values or expressions are equal. When comparing objects using this operator, it evaluates their equality based on specific rules defined by the language being used. For example, when evaluating `m == m`, the expression checks if both sides (operands) hold identical values at runtime. If they do match, then the result will evaluate as true; otherwise false[^1]. When dealing with primitive data types such as integers or strings directly compared via '==' , most modern high-level languages like Python perform value-based comparisons rather than reference ones unless explicitly stated otherwise within certain contexts involving more complex structures where references might come into play instead of actual content matching alone . Here’s an illustration demonstrating how one could implement custom behavior regarding object equivalency through overriding methods associated specifically towards handling these scenarios effectively: ```python class MyClass: def __init__(self, value): self.value = value def __eq__(self, other): if isinstance(other, MyClass): return self.value == other.value return False obj1 = MyClass(5) obj2 = MyClass(5) print(obj1 == obj2) # This would print True due to overridden method. ``` This code snippet shows that even though `obj1` and `obj2` are different instances, because we have redefined what constitutes equivalence (`__eq__`) inside our class definition according to its internal state represented here simply by integer field named *value*, now calling them equivalent returns positive outcome despite technically residing under separate memory addresses which normally wouldn't yield same results without intervention shown above.[^1] §§Related Questions§§ 1. How does type coercion affect comparison operations in JavaScript? 2. What happens during string vs numeric comparisons across various popular coding dialects including PHP & Java ? 3. Can you explain polymorphism concerning overloaded functions alongside operators discussed earlier today ? 4. Is there any performance difference between utilizing identity versus equality checks while scripting applications built upon interpreted runtimes similar to Ruby interpreter perhaps? 5. Why may relying solely upon default implementations provided natively sometimes lead unexpected bugs especially around floating point arithmetic precision issues encountered commonly amongst developers worldwide regardless experience level attained thus far along career paths chosen individually per person involved actively contributing meaningful progress forward together collaboratively achieving shared goals set forth initially agreed mutually beneficial outcomes desired ultimately reached successfully achieved efficiently effectively maintaining quality standards expected consistently throughout entire lifecycle project management process implemented properly following best practices recommended widely accepted industry wide recognized authoritative sources referenced appropriately cited correctly formatted professionally presented clearly understood easily accessible readily available whenever needed anywhere anytime instantly retrievable effortlessly navigable seamlessly integrated fully compatible cross-platform support ensured maximum portability guaranteed optimal usability realized greatest satisfaction obtained highest productivity levels maintained continuously improving constantly evolving adapting changing environments dynamically responding emerging challenges proactively addressing potential risks preemptively mitigating possible threats protectively safeguarding valuable assets preserving precious resources conserving limited supplies managing constrained budgets optimizing operational efficiencies enhancing overall effectiveness increasing measurable impacts delivering tangible benefits providing real solutions solving practical problems meeting essential needs fulfilling fundamental purposes accomplishing ultimate objectives reaching final destinations arriving predetermined endpoints completing assigned missions finishing scheduled tasks concluding planned activities terminating initiated processes ending started sequences stopping ongoing motions halting continuous actions pausing active engagements suspending current interactions interrupting direct communications breaking established connections severing existing relationships disconnecting prior associations unlinking previous attachments detaching former dependencies releasing held constraints freeing bound limitations removing imposed restrictions eliminating enforced regulations reducing excessive controls minimizing unnecessary interventions avoiding harmful interferences preventing adverse effects protecting vulnerable elements securing sensitive information ensuring privacy confidentiality guaranteeing security safety promoting health wellness supporting growth development encouraging innovation creativity fostering collaboration cooperation building trust confidence strengthening bonds unity creating harmony balance establishing peace stability maintaining order regularity enforcing discipline consistency applying logic reasoning exercising judgment decision-making practicing wisdom insight developing knowledge understanding acquiring skills competencies gaining expertise proficiency becoming masters experts excelling professionals leading authorities pioneering innovators advancing frontiers expanding horizons pushing boundaries exploring possibilities discovering opportunities reali
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值