【问题标题】:Is String a Primitive type or Object in Javascript?String 是 JavaScript 中的原始类型还是对象?
【发布时间】:2011-12-02 06:32:36
【问题描述】:

String 是 JavaScript 中的原始类型还是对象? Source 说 Undefined、Null、Boolean、Number 和 String 都是 Javascript 中的原始类型。但它说字符串也是一个对象。我糊涂了。谁能解释一下?

提前谢谢你;-)

【问题讨论】:

标签: javascript


【解决方案1】:

实际上同样的答案适用于:字符串、数字、布尔值。这些类型有它们的原始版本和对象版本,它们在应用程序运行时中强制,在后台(在您不知情的情况下)。

强制

JavaScript 是弱类型的。这意味着,每当您的代码想要使用无效数据类型执行操作(例如将字符串添加到数字)时,JavaScript 都会尝试为这种情况找到最佳匹配。

如上所述,这种机制也称为强制

基元和属性

您会发现以下代码令人困惑:

> "hello world".length
11

因为"hello world" 是字符串文字,即原语。我们知道基元没有属性。一切正常。

那么它是如何工作的呢?强制 - 原语被一个对象包裹(强制)只有一小部分时间,使用对象的属性并立即释放对象。

强制双向工作

所以原语是用它们的对象包装版本来铸造的——但它也可以反过来工作。考虑以下代码:

> String("hello ") + String("world")
"hello world"

> Number(2) + 3
5

为了完成操作,对象被向下转换为它们的原始版本。

阅读this brilliant explanation了解更多信息。

【讨论】:

    【解决方案2】:

    两者。

    有一个字符串对象,有字符串字面量。

    你可以在字面量上调用任何字符串方法,也可以在字符串对象上调用任何字符串方法。

    主要区别在于字符串对象生成一个新对象所以new String("foo") !== new String("foo")

    String 对象的类型是 "object" 而不是 "string"

    如何检查两者?

    if(typeof(s) == "string" || s instanceof String){
      //s is a string (literal or object)
    }
    

    感谢@Triynko 在 cmets 中的 sn-p

    【讨论】:

    • 别忘了"string" instanceof String 是假的,而new String() instanceof String 是真的。因此,要检查某个变量 s 是否为字符串,您必须检查 typeof(s) == "string" || s instanceof String
    【解决方案3】:

    JavaScript 既有原始字符串又有对象字符串。

    const foo = "foo"
    const bar = new String("bar");
    console.log("foo: ", foo);
    console.log("bar: ", bar);
    console.log("typeof foo: ", typeof foo);
    console.log("typeof bar: ", typeof bar);

    【讨论】:

      【解决方案4】:
      var a = "string"; 
      typeof a    // yields "string" 
      
      var a = new String('string'); 
      typeof a   // yields "object" 
      

      【讨论】:

        【解决方案5】:

        继续强制的话题:在大多数情况下,当访问任何字符串属性时(如上面的示例:"hello world".length),将字符串原语转换为对象是隐式执行的;但是在某些情况下强制可以是显式的,例如,如果对字符串调用 Array.prototype 函数,则相应的 String 实例对象(不是原语)将传递给 array 参数回调函数。这是一个可运行的示例:

        function test() {
            const str = 'abcdefgh';
            alert(Array.prototype.reduce.call(str, (result, _, i, _str) => {
                if(!i) result.push(`typeof str: ${typeof str}`);
                else if(i === 1) result.push(`typeof _str: ${typeof _str}`);
                else if(i === 2) result.push(`str instanceof String: ${str instanceof String}`);
                else if(i === 3) result.push(`_str instanceof String: ${_str instanceof String}`);
                else if(i === 4) result.push(`_str == str: ${_str == str}`);
                else if(i === 5) result.push(`_str === str: ${_str === str}`);
                else if(i === 6) result.push(`str[${i}]: "${str[i]}", _str[${i}]: "${_str[i]}"`);
                else result.push(`str: "${str}", _str: "${_str}"`);
                return result;
            }, []).join('\n'));
        }
        <button onclick="test()">Click me to run the test!</button>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-04-01
          • 2013-01-06
          • 2012-09-30
          • 2011-11-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多