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.
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.
Share Improve this question asked Jul 2, 2014 at 15:12 beingalexbeingalex 2,4765 gold badges33 silver badges72 bronze badges 02 Answers
Reset to default 17=+
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.
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.
But you could just do errors.join("\n")
instead, much easier!