繁体   English   中英

如何使用JavaScript获取字符串形式的数组内的数组

[英]How to get the arrays inside an array which is in the form of string using javascript

我对Java和javascript很陌生,但是我遇到了问题。

我有一个字符串形式的数组,看起来像下面的javascript。

[[0,'Apple','Banana'],['The Apple fruit, comes from Apple Tree', 'The Banana fruit, comes from Banana Tree']]

在这种情况下,我需要获取第一个数组[0,'Apple','Banana']并将其保存为单独的数组,然后我需要获取第二个数组['The Apple fruit, comes from Apple Tree', 'The Banana fruit, comes from Banana Tree']并在这样的文本区域中将其显示为文本。

苹果果实,来自苹果树
香蕉果实,来自香蕉树

如何在javascript中实现呢?

由于我已经在Google上集中搜索此问题,因此需要一些帮助。

提前致谢。

您可以使用var arr = JSON.parse(str)将字符串转换为Javascript数组。 然后名义上访问数组的成员,例如。 arr[0]

“在JavaScript中如下所示”意味着您对我有一个字符串数组。

  1. 如果你有这个

     var myarray = [ [0,'Apple','Banana'], ['The Apple fruit, comes from Apple Tree', 'The Banana fruit, comes from Banana Tree'] ]; 

    只需将数组分配给变量

     var first = myarray[0]; 

    对于第二个问题,使用数组的.join()方法

     var second = myarray[1].join(' '); 
  2. 或者如果你有

     var mystring = "[[0,'Apple','Banana'],['The Apple fruit, comes from Apple Tree', 'The Banana fruit, comes from Banana Tree']]"; 

    那么您需要先转换为数组。

     var myarray = JSON.parse(mystring); 

如果您有字符串,则可以执行以下操作。

var arr = JSON.parse("[[0,'Apple','Banana'],['The Apple fruit, comes from Apple Tree', 'The Banana fruit, comes from Banana Tree']]");

var seprateArr = arr[0];

var text = arr[1].join(" ");

尝试这个

var a =eval("[[0,'Apple','Banana'],['The Apple fruit, comes from Apple Tree', 'The Banana fruit, comes from Banana Tree']]");
var b = a[0];
var c = a[1];

现在b和c是您的新数组;

您也可以使用mohkhan提到的上述方法,但这不是有效的json; 如果您有有效的JSON字符串,则首选方法是1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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