Javascript中字符串原语和字符串包装器对象之间的区别

时间:2015-06-22 15:53:32

标签: javascript string primitive string-literals

我对wrapper objects for primitives的内容感到非常困惑。例如,字符串基元和使用字符串包装器对象创建的字符串。

<tbody>
  {% for currentCompteur in compteurs %}
    <tr>
      <td>{{ currentCompteur.matriculeCompteur}}</td>
      <td>{{ currentCompteur.miseEnService|date("Y-m-d", "Europe/Paris")}}</td>
      <td>{{ currentCompteur.miseHorsService|date("Y-m-d", "Europe/Paris")}}</td>
      <td class="no-cell-padding">
        <table class="inner-table table stripe row-border order-column display table-bordered table-hover compact" cellspacing="0" width="100%">
            <tr>
              <td>code for parametresMesure</td>
              <td>code for parametresMesure</td>
              <td>code for parametresMesure</td>
              <td>code for parametresMesure</td>
            </tr>
        </table>
      </td>
    </tr>
  {% endfor %}
</tbody>

两者都允许访问var a = "aaaa"; var b = new String("bbbb"); console.log(a.toUpperCase()); // AAAA console.log(b.toUpperCase()); // BBBB console.log(typeof a); // string console.log(typeof b); // object 方法,并且似乎就像字符串文字一样。但一个不是字符串,它是一个对象。 String.prototypea之间的实际区别是什么?为什么要使用b创建字符串?

1 个答案:

答案 0 :(得分:2)

原始字符串不是对象。对象字符串是一个对象。

基本上,这意味着:

  • 通过引用比较对象字符串,而不是通过它们包含的字符串进行比较

    "aaa" === "aaa";                         // true
    new String("aaa") === new String("aaa"); // false
    
  • 对象字符串可以存储属性。

    function addProperty(o) {
      o.foo = 'bar'; // Set a property
      return o.foo;  // Retrieve the value
    }
    addProperty("aaa");             // undefined
    addProperty(new String("aaa")); // "bar"