javascript:原始字符串有方法吗?

发布于 2024-11-02 23:15:36 字数 422 浏览 5 评论 0原文

MDN 指出:

原始,原始值

数据不是对象,而是 没有任何方法。 JavaScript 有 5 个 原始数据类型:字符串、数字、 布尔值、空、未定义。随着 null 和未定义的例外,所有 基元值有对象 环绕的等价物 原始值,例如 String 对象 环绕一个字符串原语。全部 原语是不可变的。

因此,当我们调用 "s".replace"s".anything 时,它相当于 new String("s").replacenew String("s").anything

MDN states:

primitive, primitive value

A data that is not an object and does
not have any methods. JavaScript has 5
primitive datatypes: string, number,
boolean, null, undefined. With the
exception of null and undefined, all
primitives values have object
equivalents which wrap around the
primitive values, e.g. a String object
wraps around a string primitive. All
primitives are immutable.

So when we call a "s".replace or "s".anything is it equivalent to new String("s").replace and new String("s").anything?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽梦忆笙歌 2024-11-09 23:15:36

不,字符串基元没有方法。与数字基元一样,JavaScript 运行时会在以下构造调用时将它们提升为成熟的“字符串”对象:

var space = "hello there".indexOf(" ");

在某些语言中(特别是 Java,但我认为该术语很常用)表示该语言在适当的时候将原语“装箱”在其对象包装器中。对于数字来说,由于标记语法的变幻莫测,情况会稍微复杂一些。你不能只说

var foo = 27.toLocaleString();

因为“.”不会按照您需要的方式进行解释;但是:

var foo = (27).toLocaleString();

工作正常。对于字符串基元(以及布尔值),语法并不含糊,因此例如:

var foo = true.toString();

会起作用。

No, string primitives do not have methods. As with numeric primitives, the JavaScript runtime will promote them to full-blown "String" objects when called upon to do so by constructs like:

var space = "hello there".indexOf(" ");

In some languages (well, Java in particular, but I think the term is in common use) it's said that the language "boxes" the primitives in their object wrappers when appropriate. With numbers it's a little more complicated due to the vagaries of the token grammar; you can't just say

var foo = 27.toLocaleString();

because the "." won't be interpreted the way you'd need it to be; however:

var foo = (27).toLocaleString();

works fine. With string primitives — and booleans, for that matter — the grammar isn't ambiguous, so for example:

var foo = true.toString();

will work.

救星 2024-11-09 23:15:36

技术上正确的答案是“不”。

现实世界的答案是“不,但无论如何它都会起作用”。这是因为,当您执行诸如解释器之类的操作时

"s".replace()

,解释器知道您想要实际对字符串进行操作,就好像您是用它创建的一样

var str = new String("s")

,因此就像您已经这样做了一样。

The technically correct answer is "no".

The real-world answer is "no, but it will work anyway". That's because when you do something like

"s".replace()

the interpreter knows that you want to actually operate on the string as if you had created it with

var str = new String("s")

and therefore acts as if you had done that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文