0

I have the following javascript:

var emails_array = ["[\"theiremail1\",\"theiremail2\",\"theiremail3\"]"];
var emails_array_length = emails_array.length;
alert("emails array: " + emails_array + "emails array length: " + emails_array_length);

The alert that appears as the result of this code is:

emails array: ["theiremail1","theiremail2","theiremail3"]emails array length: 1

Why isn't it returning 3?

2 Answers 2

1

That's an array with only one item:

var emails_array = [
    "[\"theiremail1\",\"theiremail2\",\"theiremail3\"]"
];

What you're likely after:

var emails_array = JSON.parse(["[\"theiremail1\",\"theiremail2\",\"theiremail3\"]"]);

http://jsfiddle.net/wtLo7h7s/

Sign up to request clarification or add additional context in comments.

Comments

0

I think because of the escape characters and your initial double quotes "". I have tested this a couple times and everytime I use your syntax of var emails_array = ["[\"theiremail1\",\"theiremail2\",\"theiremail3\"]"]; the length comes out 1 because of the initial quotes.

Perhaps a simpler string would work?

For certain, var emails_array = ['theiremail1', 'theiremail2', 'theiremail3']; will provide an emails_array.length of 3...

This gives me a .length of 3 in my test environment anyway. If you MUST use your original double bracketing because you actually want a string with brackets in it then the following works for me.

emails_array = ['[theiremail1', 'theiremail2', 'theiremail3]']; which will have a [ in position 0 and ] in position 2 if thats what you want.

The way you currently have your array setup it is actually only 1 length long because your first double quotes "" tell the compiler to see everything as one big string and it cannot see your delimiter , character.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.