为什么在字符串上+++会产生奇怪的结果 [英] Why + + on strings gives strange result

查看:102
本文介绍了为什么在字符串上+++会产生奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery动态附加元素,发现使用+ +时会显示NaN并且未添加下一个文本.

I was working on appending the element dynamically using jQuery and found that when using + + it shows NaN and the next text is not added.

我可以猜测+ +在这里以算术加运算符的方式工作并返回NaN.

I can guess that somehow + + works here as Arithmetic plus operator and returns NaN.

这不是增量运算符,因为两个+之间有空格.

This is not Increment operator as there is space between the two +.

我的问题是

  1. 这里实际上发生了什么,所以它返回NaN
  2. 为什么+在被字符串包围时不能用作串联运算符.
  1. What is actually happening here so it returns NaN
  2. Why + here does not work as concatenation operator when it is surrounded by strings.

$('#message').html('<span>' + + ' new message</span>');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>

在Node.js中可以看到相同的行为

The same behaviour can be seen in Node.js

> 'a' + + 'b' // aNaN

注意::我知道我在这里添加了一个额外的+并将其删除将对我有用.

Note: I know that I've added an extra + here and removing that will work for me.

推荐答案

原因是因为将+字符放在字符串之前,是您试图将'b'字符串转换为数字,结果导致NaN.您问题中的代码与此等效:

The reason is because by placing the + character before a string you're attempting to convert the 'b' string to a number, which results in NaN. The code in your question is equivalent to this:

'a' + Number('b')

因此,Number('b')返回NaN,然后将其强制为字符串并附加到a.这种行为是JS固有的,因此所使用的库(无论是jQuery,节点还是其他任何库)都是无关紧要的.

Hence Number('b') returns NaN which is then coerced to a string and appended to a. This behaviour is intrinsic to JS, so the library being used (whether jQuery, node or any other) is irrelevant.

这篇关于为什么在字符串上+++会产生奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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