简体   繁体   中英

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. 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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM