javascript - 在 JavaScript 中使用++ 时的奇怪行为

标签 javascript string concatenation

每个人都知道 JavaScript 中两个字符串的基本连接:

> "Hello " + "World!"
'Hello World!'

但是如果我们使用 + + 而不是 + 会发生什么?我刚遇到以下奇怪行为:

> "Hello " + + "World!"
'Hello NaN'
> "Hello " + + ""
'Hello 0'

从上面的例子中,我可以看到第二个字符串被转换为数字。因此,将具有 valueOf 属性的对象作为函数传递,该函数返回的值将被转换。

> "Hello " + + ({valueOf: function () {return 1; }})
'Hello 1'

正如预期的那样,它显示 "Hello 1"


为什么在Number中转换第二个字符串?为什么不抛出语法错误?

最佳答案

第二个 +unary plus operator其目的是将其操作数转换为数字。

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

"Hello " + + "World!"

只能解析为

"Hello " + (+ "World!")

这是

"Hello " + NaN

因此你的结果。

这个一元运算符在 JavaScript 中非常有用,是将数字或字符串转换为数字的最常用方法之一。与 parseFloat 相比,它还有一个优势,那就是它不是可笑的容忍度(parseFloat("7up") 会返回 7),这使它成为一种简单的方法查看字符串是否表示数字(只需测试 s==+s)。

关于javascript - 在 JavaScript 中使用++ 时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25533941/

相关文章:

javascript - 用相同的类包裹相邻的元素

javascript - 使用 URI.js 构建 url

python - 多尺度 CNN - Keras 实现

javascript - 滚动时增量值 '0.1'

javascript - Angular ui-router向url添加哈希

php - 计算字符串中某个字符串出现的次数

string - 如何使用 swift 从 sqlite3 db 检索字符串字段

PHP mySQL - 替换字符串中的一些字符串

c - 拆分从套接字接收的字符数组的最佳方法

用于连接两个 Bstr 字符串的 C++ 代码