在Javascript中,字符串是原始类型还是对象?

48

在 JavaScript 中,字符串是原始类型还是对象?来源说未定义、空值、布尔、数字和字符串都是 JavaScript 中的原始类型,但同时也说字符串也是一个对象。我很困惑,请有人能解释一下吗?

提前感谢你的帮助;-)


http://stackoverflow.com/questions/2811092/does-string-inherit-from-object-in-javascript http://www.sitepoint.com/oriented-programming-1/ - Dmytro Shevchenko
6个回答

47

实际上,同样的答案适用于:字符串、数字、布尔值。这些类型有其原始值和对象版本,在应用程序运行时,在幕后进行强制类型转换(而不需要您的知识)。

类型转换

JavaScript 是弱类型语言。这意味着,只要您的代码想使用无效数据类型执行操作(例如将字符串添加到数字中),JavaScript 将尝试找到最佳匹配以完成此操作。

这个机制也被称为上面提到的强制类型转换

原始值和属性

以下代码可能会让您感到困惑:

> "hello world".length
11

因为"hello world"是一个字面字符串,也就是一个原始值。我们知道原始值没有属性。一切都正确。

那么这是如何工作的呢?类型转换 - 原始值被包装成对象(强制转换),仅在极短的时间内使用对象的属性,然后立即释放该对象。

双向类型转换

因此,原始值被转化为它们对象包装版本的形式 - 但它也可以反过来。考虑以下代码:

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

> Number(2) + 3
5

为了执行操作,这些对象被向下转换为它们的基本版本。

阅读这篇精彩的解释以了解更多。


32

两者都可以。

有一个String对象和一些字符串文字。

您可以在文字上调用任何字符串方法,也可以在字符串对象上调用任何字符串方法。

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

还有,String对象的类型为"object"而不是"string"

如何检查两者?

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

致谢@Triynko在评论中提供的片段。


4
请注意,""string" instanceof String为false,而new String() instanceof String为true。因此,要检查某个变量s是否为字符串,您必须检查typeof(s) == "string" || s instanceof String - Triynko

10

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);


1
var a = "string"; 
typeof a    // yields "string" 

var a = new String('string'); 
typeof a   // yields "object" 

1
继续讨论强制转换:在大多数情况下,当访问任何字符串属性时(例如上面的示例:"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>


0

这是一个非常基础的实用函数,我经常使用它

const isString = (s, instance = false) => {
  return typeof s === 'string' || (instance && s instanceof String)
}

const foo = 'lalalalala'
const faa = new String('bababababab')
const fnc = () => {}

console.log(`foo is string primitive: ${isString(foo)}`)
console.log(`faa is string primitive: ${isString(faa)}`)

console.log(`foo is string primitive or object: ${isString(foo, true)}`)
console.log(`faa is string primitive or object: ${isString(faa, true)}`)
console.log(`fnc is string primitive or object: ${isString(fnc, true)}`)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接