[英]javascript/json .length returning 1 for array of length 3
I have the following javascript: 我有以下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? 为什么不返回3?
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\"]"]);
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\\"]"];
我已经测试了几次,每次使用您的语法
var emails_array = ["[\\"theiremail1\\",\\"theiremail2\\",\\"theiremail3\\"]"];
the length comes out 1 because of the initial quotes. 长度因初始引号而为1。
Perhaps a simpler string would work? 也许更简单的字符串可以工作?
For certain, var emails_array = ['theiremail1', 'theiremail2', 'theiremail3'];
可以肯定的是,
var emails_array = ['theiremail1', 'theiremail2', 'theiremail3'];
will provide an emails_array.length
of 3... 将提供一个
emails_array.length
为3 ...
This gives me a .length
of 3
in my test environment anyway. 无论如何,这使我在测试环境中的
.length
为3
。 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. 这将有一个
[
0位置]
在位置2如果那是你想要的。
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. 当前保存在您的阵列安装的方式,它实际上只有1个长度长,因为你的第一个双引号
""
告诉编译器看到的一切,作为一个大的字符串,它不能看到你的分隔符,
字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.