NaN in Javascript string concatenation

Take this array:

errors [
    "Your name is required.", 
    "An email address is required."
]

I am trying to iterate and create a line 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 get NaNin the console. Why is this and how to fix it?

Thanks in advance.

+4
source share
2 answers

=+does not match with +=. First x = +y, and another - x = x + y.

+xis a shortcut for Number(x)literally converting a variable to a number. If the operation cannot be completed, returns NaN.

+=acts like a string concatenation when one of the parts (left or right) is of type string.

+11
source

, , , =+ +=. :

str = (+error) + "\n";

+error error , NaN, , .

errors.join("\n"), !

+8

Source: https://habr.com/ru/post/1546878/


All Articles