字符串是Java语言中的原始类型还是对象? [英] Is String a Primitive type or Object in Javascript?

查看:47
本文介绍了字符串是Java语言中的原始类型还是对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串是Java语言中的原始类型还是对象?消息来源说Undefined,Null,Boolean,Number和String都是Javascript中的原始类型.但是它说String也是Object.我很困惑.有人可以解释吗?

Is String a Primitive type or Object in Javascript? Source says Undefined, Null, Boolean, Number and String are all primitive types in Javascript. But it says String is an Object too. I'm confused. Can someone please explain?

提前谢谢;-)

推荐答案

实际上,相同的答案适用于:字符串,数字,布尔值.这些类型具有其原始版本和对象版本,这些版本在应用程序运行时的内部(在您不知情的情况下)被强制.

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的类型很弱.这意味着每当您的代码想要对无效数据类型执行操作(例如,将字符串添加到数字中)时,JavaScript都会尝试找到这种情况下的最佳匹配.

JavaScript is weakly typed. 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.

如上所述,该机制也称为胁迫.

This mechanism is also called, as mentioned above, coercion.

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

You can find following code confusing:

> "hello world".length
11

因为"hello world"是字符串文字,即 primitive .而且我们知道原始元素没有属性.没事.

because "hello world" is a string literal, i.e. a primitive. 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.

阅读这个绝妙的解释了解更多信息.

这篇关于字符串是Java语言中的原始类型还是对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆