JavaScript中新String(“x”)的重点是什么? [英] What's the point of new String("x") in JavaScript?

查看:161
本文介绍了JavaScript中新String(“x”)的重点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行新字符串(已经是字符串)的用例是什么?

什么是它的全部意义?

推荐答案

String 的实际用途很少由 new String(foo)创建的对象。 String 对象超过原始字符串值的唯一优势是,它可以存储属性作为对象:

There's very little practical use for String objects as created by new String("foo"). The only advantage a String object has over a primitive string value is that as an object it can store properties:

var str = "foo";
str.prop = "bar";
alert(str.prop); // undefined

var str = new String("foo");
str.prop = "bar";
alert(str.prop); // "bar"

如果您不确定可以将哪些值传递给您的代码,那么我会建议你在项目中遇到更大的问题。没有返回字符串的本机JavaScript对象,主要库或DOM方法将返回 String 对象而不是字符串值。但是,如果您想要绝对确定您有一个字符串值而不是 String 对象,您可以按如下方式转换它:

If you're unsure of what values can be passed to your code then I would suggest you have larger problems in your project. No native JavaScript object, major library or DOM method that returns a string will return a String object rather than a string value. However, if you want to be absolutely sure you have a string value rather than a String object, you can convert it as follows:

var str = new String("foo");
str = "" + str;

如果您检查的值可能是任何对象,则您的选项如下:

If the value you're checking could be any object, your options are as follows:


  1. 不要担心String对象,只需使用typeof 。这是我的建议。

typeof str ==string

使用instanceof以及typeof 。这通常有效,但缺点是在另一个窗口中创建的String对象返回假阴性。

Use instanceof as well as typeof. This usually works but has the disadvantage of returning a false negative for a String object created in another window.

typeof str ==string| | str instanceof String

使用鸭子打字 。检查是否存在一个或多个特定于String的方法,例如substring()或toLowerCase()。这显然是不精确的,因为它会为碰巧有一个带有你正在检查的名称的方法的对象返回误报,但在大多数情况下它会足够好。

Use duck typing. Check for the existence of one or more String-specific methods, such as substring() or toLowerCase(). This is clearly imprecise, since it will return a false positive for an object that happens to have a method with the name you're checking, but it will be good enough in most cases.

typeof str ==string|| typeof str.substring ==function

这篇关于JavaScript中新String(“x”)的重点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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