[英]NaN in Javascript string concatenation
Take this array: 拿这个数组:
errors [
"Your name is required.",
"An email address is required."
]
I am trying to iterate it and create a string like: 我试图迭代它并创建一个字符串,如:
"Your name is required.\nAn email address is required.\n"
Using this code: 使用此代码:
var errors = ["Your name is required.","An email address is required."];
if (errors) {
var str = '';
$(errors).each(function(index, error) {
str =+ error + "\n";
});
console.log(str); // NaN
}
I am getting NaN
in the console. 我在控制台中获得了
NaN
。 Why is this and how do I fix it? 为什么这样,我该如何解决?
Thanks in advance. 提前致谢。
=+
is not the same as +=
. =+
与+=
。 First is x = +y
and another is x = x + y
. 首先是
x = +y
,另一个是x = x + y
。
+x
is a shortcut for Number(x)
literally converting the variable to number. +x
是Number(x)
字面上将变量转换为Number(x)
的快捷方式。 If the operation can't be performed, NaN
is returned. 如果无法执行操作,则返回
NaN
。
+=
acts like string concatenation when one of the parts (left or right) has a string
type. +=
当其中一个部分(左侧或右侧)具有string
类型时,它就像字符串连接一样。
The reason you're getting that result is because you are writing =+
instead of +=
. 你得到这个结果的原因是因为你写的是
=+
而不是+=
。 It's being treated as: 它被视为:
str = (+error) + "\n";
+error
casts error
to a number, which would be NaN
because it can't be converted, so there you go. +error
蒙上error
的数量,这将是NaN
,因为它不能被转换,所以你去。
But you could just do errors.join("\\n")
instead, much easier! 但你可以做
errors.join("\\n")
而不是更容易!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.