繁体   English   中英

String 是原始类型还是 Javascript 中的 Object?

[英]Is String a Primitive type or Object in Javascript?

String 是原始类型还是 Javascript 中的 Object? Source说Undefined,Null,Boolean,Number和String都是Javascript中的原始类型。 但它说 String 也是 Object 。 我很困惑。 有人可以解释一下吗?

先感谢您;-)

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

强迫

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

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

原语和属性

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

> "hello world".length
11

因为"hello world"是一个字符串文字,即一个原始的. 我们知道基元没有属性 一切都对。

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

强制双向工作

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

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

> Number(2) + 3
5

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

阅读这个精彩的解释以了解更多信息。

两个都。

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

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

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

那和一个字符串对象是类型"object"而不是"string"

如何检查两者?

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

评论中的片段归功于@Triynko

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

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

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

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

这是我一直使用的一个非常基本的实用程序 function

 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)}`)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM