最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

NaN in Javascript string concatenation - Stack Overflow

programmeradmin1浏览0评论

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 0
Add a comment  | 

2 Answers 2

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!

发布评论

评论列表(0)

  1. 暂无评论