javascript - Typescript/Javascript - 使用 new String() 和 s = '' 声明变量

标签 javascript typescript

应该如何声明字符数组或字符串?不确定字符数组和字符串之间是否有区别。

let operators = new String();

let operators = '';

最佳答案

javascript 中没有字符数组,typescript 中也没有字符数组(这是 javascript 的超集)。

'' 是一个 String 对象。它被称为文字形式。

['a', 'b', 's'] 是一个 String 对象数组。

所以只需使用'';

现在 ''String 之间有什么区别。第一个是基元,第二个是对象。但无论它们与第一个 JavaScript 相同,都会自动包装它并为其构造一个 String 对象。这样我们就可以使用字符串对象的所有方法了! 与 eval() 一起使用时除外。 原语被视为代码源String 对象 被视为字符串。 并且原语仍然与对象不同。但就功能而言,它们是相同的。

这里展示了与 console.log() 的区别

enter image description here

从一般编程的 Angular 来看!他们是一样的!而且差异根本不重要。少数情况下!就像 eval 或 console.log 一样。引擎的默认处理可能不同。但无论如何,无论你在这些案件中很少遇到什么。现在一切都清楚了。该文档显示了更多更好的内容,请阅读下面的引用。

更好地查看此处的文档引用链接:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

引用:

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of Boolean and Numbers.)

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (that is, called without using the new keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

let s_prim = 'foo'
let s_obj = new String(s_prim)

console.log(typeof s_prim) // Logs "string"
console.log(typeof s_obj)  // Logs "object"

String primitives and String objects also give different results when using eval(). Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

let s1 = '2 + 2'              // creates a string primitive
let s2 = new String('2 + 2')  // creates a String object
console.log(eval(s1))         // returns the number 4
console.log(eval(s2))         // returns the string "2 + 2"

For these reasons, the code may break when it encounters String objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.

A String object can always be converted to its primitive counterpart with the valueOf() method.

console.log(eval(s2.valueOf()))  // returns the number 4

关于javascript - Typescript/Javascript - 使用 new String() 和 s = '' 声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59538914/

相关文章:

javascript - Safari MediaSource 永远不会在后台选项卡中打开

javascript - 通过 jQuery 在鼠标悬停时更改按钮文本

函数内的 Angular 访问变量

reactjs - 如何将 react with typescript 添加到现有的 asp.net core mvc 应用程序

javascript - 使用单引号传递 json 编码的字符串

javascript - 使用 :lt(3) Selector 为每个元素设置不同的背景颜色

javascript - 非异步路径返回什么?

angular - 如何清除 Angular 中的 div 内容? ( Angular 7)

typescript - 如何在函数上使用泛型类型,该类型必须满足特定条件?

angular typescript 自定义命名空间