简体   繁体   English

从数组格式的字符串创建Javascript数组

[英]Create a Javascript array from an array formatted string

I'm getting a string (which has array markup) from a CMS but it is not being recognized as an array by javascript 我从CMS获取一个字符串(具有数组标记),但是javascript无法将其识别为数组

// Example of how data comes from CMS
var data = [ ["<div class='example'><h2>University</h2><hr><p>Lorem Ipsum</p></div>", 13.3851, -2.2568, "/example.png"],       
["<div class='example2'><h2>University Two</h2><hr><p>Lorem Ipsum Example</p></div>", -3.3851, -22.2568, "/examplenow.png"], ] ;

// where I need data as array
googlelocations = data;

when I log data I get: 当我记录数据时,我得到:

0: "[\"<div class='example'><h2>University</h2><hr><p>Lorem Ipsum</p></div>\", -3.3851, -22.2568, \"/example.png\"],\r\n[\"<div class='example2'><h2>University Two</h2><hr><p>Lorem Ipsum Example</p></div>\", -3.3851, -22.2568, \"/examplenow.png\"],"

​ length: 1 How do I get the var data to be an array of the above info? 长度:1如何获取var数据作为上述信息的数组?

Assuming you are getting 假设你正在

["<div class='example'><h2>University</h2><hr><p>Lorem Ipsum</p></div>", 13.3851, -2.2568, "/example.png"],       
["<div class='example2'><h2>University Two</h2><hr><p>Lorem Ipsum Example</p></div>", -3.3851, -22.2568, "/examplenow.png"],

from the CMS as something like @DATA. 来自CMS的@DATA。

You need to wrap these Arrays into an Array of Arrays in order for them to be properly assigned into the data variable. 您需要将这些数组包装到数组数组中,以便将它们正确分配到data变量中。

var data = [ @DATA ];

To parse that response, that seems to be an array, you could use JSON.parse() , in such a case you need to build a valid array or js object. 要解析似乎是一个数组的响应,可以使用JSON.parse() ,在这种情况下,您需要构建一个有效的数组或js对象。 In this case adding [ ] solves the issue, but it depends on how is exactly the response. 在这种情况下,添加[ ]可以解决问题,但这取决于响应的准确程度。

 var data = "[\\"<div class='example'><h2>University</h2><hr><p>Lorem Ipsum</p></div>\\", -3.3851, -22.2568, \\"/example.png\\"],\\r\\n[\\"<div class='example2'><h2>University Two</h2><hr><p>Lorem Ipsum Example</p></div>\\", -3.3851, -22.2568, \\"/examplenow.png\\"]" data = JSON.parse("["+data+"]") console.log(data) 

If you want just the values, you could do instead, something like: 如果只需要这些值,则可以执行以下操作:

 var data = "[\\"<div class='example'><h2>University</h2><hr><p>Lorem Ipsum</p></div>\\", -3.3851, -22.2568, \\"/example.png\\"],\\r\\n[\\"<div class='example2'><h2>University Two</h2><hr><p>Lorem Ipsum Example</p></div>\\", -3.3851, -22.2568, \\"/examplenow.png\\"]" data = data.split(",") var latLong = [data[1],data[2],data[5],data[6]] console.log(latLong) 

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

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