javascript - 文字和对象——什么时候使用什么?

标签 javascript

我想知道什么时候使用文字以及什么时候使用对象来创建数据类型值。

例如。

我什么时候使用这些:

/regexp/
"string"

当这些:

new RegExp("regexp")
new String("string")

这些会给我相同的方法和属性吗?

最佳答案

new RegExp() 在您想要连接存储在变量中的值时非常有用。

var x = "exp";
var regex = new RegExp("reg" + x);

不过,我不知道有什么理由不使用字符串文字。

使用构造函数可能会得到意外结果的一个示例是在创建数组时。

var arr = new Array( 3 ); // creates an Array with an initial length of 3

var arr = new Array( "3" ); // creates an Array with an initial length of
                            //    1 item that has the value "3"

总的来说,我认为坚持使用文字是安全的。

关于javascript - 文字和对象——什么时候使用什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3756046/

相关文章:

javascript - 如何在 HTML 中引用对象中的方法

javascript - 根据操作验证表单

javascript - 如何使用 Jquery 获取 pickadate 值?

javascript - Angular JS : Mix of Fixed + Dynamic columns

V8 的 JavaScript 标准库

javascript - 防止以html形式进行android单词预测

javascript - 如何修复 ClearInterval

javascript - Jquery Mobile Navbar 轮廓/边框颜色

javascript - 如何使用鼠标单击选择多个元素?

javascript - 将日期转换为 Word 格式