[英]Is String a Primitive type or Object in Javascript?
Is String a Primitive type or Object in Javascript? String 是原始类型还是 Javascript 中的 Object? Source says Undefined, Null, Boolean, Number and String are all primitive types in Javascript.
Source说Undefined,Null,Boolean,Number和String都是Javascript中的原始类型。 But it says String is an Object too.
但它说 String 也是 Object 。 I'm confused.
我很困惑。 Can someone please explain?
有人可以解释一下吗?
Thank you in advance;-)先感谢您;-)
Actually the same answer applies to: strings, numbers, booleans .实际上,同样的答案适用于:字符串、数字、布尔值。 These types have their primitive and object version which are coerced in the application runtime, under the hood (without your knowledge).
这些类型有它们的原始版本和对象版本,它们在应用程序运行时被强制执行,在幕后(在您不知情的情况下)。
JavaScript is weakly typed. JavaScript 是弱类型的。 This means that whenever your code wants to perform an operation with invalid datatypes (such as add a string to a number), JavaScript will try to find a best match for this scenario.
这意味着,无论何时您的代码想要使用无效数据类型执行操作(例如向数字添加字符串),JavaScript 都会尝试为这种情况找到最佳匹配。
This mechanism is also called, as mentioned above, coercion .如上所述,这种机制也称为强制。
You can find following code confusing:您会发现以下代码令人困惑:
> "hello world".length
11
because "hello world"
is a string literal, ie a primitive .因为
"hello world"
是一个字符串文字,即一个原始的. And we know that primitives don't have properties .我们知道基元没有属性。 All is right.
一切都对。
So how does that work?那么它是如何工作的呢? Coercion - the primitive is wrapped with an object (coerced) for just a tiny fraction of time, the property of the object is used and immediately the object gets disposed.
强制 - 原语被一个对象(强制)包裹了一小部分时间,使用对象的属性并立即处理对象。
So primitives are casted with their object wrapping versions - but it also works the other way round as well.所以基元是用它们的对象包装版本来铸造的——但它也可以反过来工作。 Consider following code:
考虑以下代码:
> String("hello ") + String("world")
"hello world"
> Number(2) + 3
5
The objects are down-casted to their primitive versions in order to accomplish the operation.为了完成操作,对象被向下转换为它们的原始版本。
Read this brilliant explanation to learn more.阅读这个精彩的解释以了解更多信息。
There is a String object and there are string literals.有一个 String 对象和字符串文字。
You can call any string method on a literal and you can call any string method on a string object.您可以对文字调用任何字符串方法,也可以对字符串对象调用任何字符串方法。
The major difference is that a string object generates a new object so new String("foo") !== new String("foo")
主要区别在于字符串对象会生成一个新对象,所以
new String("foo") !== new String("foo")
That and a String object is type "object"
and not "string"
那和一个字符串对象是类型
"object"
而不是"string"
if(typeof(s) == "string" || s instanceof String){
//s is a string (literal or object)
}
Credits to @Triynko for the snippet in the comments评论中的片段归功于@Triynko
JavaScript has both primitive and object Strings. 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"
To continue the topic of coercion: in most cases, when any string property is accessed (like in the example above: "hello world".length
), converting a string primitive to an object is performed implicitly;继续强制转换的话题:在大多数情况下,当访问任何字符串属性时(如上面的示例:
"hello world".length
),将字符串原语转换为对象是隐式执行的; however in some cases coercion can be explicit , like, for example, if to call Array.prototype
functions upon strings, the respective String instance object (NOT a primitive) is passed to an array
argument of the callback function.然而,在某些情况下,强制转换可以是显式的,例如,如果在字符串上调用
Array.prototype
函数,则将相应的 String 实例对象(不是基元)传递给回调函数的array
参数。 Here is a runnable example:这是一个可运行的示例:
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>
This is a very basic utility function that I use all the time这是我一直使用的一个非常基本的实用程序 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.