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. 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
is a shortcut for Number(x)
literally converting the variable to number. If the operation can't be performed, NaN
is returned.
+=
acts like string concatenation when one of the parts (left or right) has a string
type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With