JavaScript 中的 new String("x") 有什么意义? [英] What's the point of new String("x") in JavaScript?

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

问题描述

new String("already a string") 的用例是什么?

它的全部意义是什么?

推荐答案

new String("foo") 创建的 String 对象几乎没有实际用途.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

使用鸭子打字.检查是否存在一个或多个特定于字符串的方法,例如 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 中的 new String("x") 有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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