2014-10-08 127 views
0

我有以下的JavaScript阵列返回1:的JavaScript/JSON。长度为长度3

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

显示为这个代码的结果的警报是:

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

为什么ISN”它返回3吗?

回答

1

这是一个阵列,只有一个项目:

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

你怎么可能后:

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

http://jsfiddle.net/wtLo7h7s/

+0

这样做。谢谢。 – Philip7899 2014-10-08 17:13:01

0

我想是因为转义字符和您最初的双引号""。我已经测试了几次,并且每次使用var emails_array = ["[\"theiremail1\",\"theiremail2\",\"theiremail3\"]"];的语法时,由于最初的引号,所以长度出现1。

也许一个简单的字符串可以工作?

肯定的,var emails_array = ['theiremail1', 'theiremail2', 'theiremail3'];将提供3的emails_array.length ...

这给我的3一个.length在我的测试环境反正。如果你必须使用你原来的双包围,因为你实际上需要一个带有括号的字符串,那么以下内容适用于我。

emails_array = ['[theiremail1', 'theiremail2', 'theiremail3]'];它将在位置0有一个[和在位置2有]如果这就是你想要的。

当前你的数组设置的方式实际上只有1个长度,因为你的第一个双引号""告诉编译器将所有东西看作一个大字符串,并且它看不到你的分隔符,字符。