javascript:原始字符串有方法吗? [英] javascript: do primitive strings have methods?
问题描述
MDN 声明:
原始值,原始值
不是对象且
没有任何方法的数据。 JavaScript有5
原始数据类型:string,number,
boolean,null,undefined。对于null和undefined的
异常,所有
基元值都具有对象
等价物,它包围
原始值,例如:一个String对象
包装一个字符串原语。所有
原语都是不可变的。
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.
所以当我们调用s.replace
或s.anything
相当于 new String(s)。replace
和新字符串(s)。任何
?
So when we call a "s".replace
or "s".anything
is it equivalent to new String("s").replace
and new String("s").anything
?
推荐答案
否,字符串原语没有方法。与数字原语一样,JavaScript运行时会通过以下结构将它们提升为完整的String对象:
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(" ");
在某些语言中(特别是Java,但我认为这个术语是常用的)它是说该语言在适当的时候封装对象包装器中的原语。由于令牌语法的变幻莫测,数字有点复杂;你不能只说
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();
将有效。
这篇关于javascript:原始字符串有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!