java中String是原始数据类型,字符串是Java语言中的原始类型还是对象?

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?

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

Coercion

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.

Primitives and Properties

You can find following code confusing:

> "hello world".length

11

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.

Coercion working both ways

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值