js字符串(String)转多维数组(Array) - 代码篇
Demo代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js字符串(String)转多维数组(Array)</title>
</head>
<body>
<script type="text/javascript">
// 类数组对象
var obj = {
"data": {
"sites": [
{ "id": "1", "name": "菜鸟教程", "url": "www.runoob.com" },
{ "id": "2", "name": "菜鸟工具", "url": "c.runoob.com" },
{ "id": "3", "name": "Google", "url": "www.google.com" }
],
"details": [
{ "id": "1", "ak": "1e34d4aff67e98ga56g2", "tips": "网址1" },
{ "id": "2", "ak": "6jih56s0vvp89095mqql", "tips": "网址2" },
{ "id": "3", "ak": "80fds23kocpo6suyrlyz", "tips": "网址3" },
]
}
}
//====================
//========方法1 JSON.parse()效率高============
var str = 'dog,[cat,lion],[bird,chicken,duck]';
var strArr = JSON.parse('['+str.replace(/\w+/g, function(a){return '"'+a+'"'})+']')
console.log(strArr)
//========方法2 eval() 效率偏低============
var str = 'dog,[cat,lion],[bird,chicken,duck]';
var strArr = eval('['+str.replace(/\w+/g, function(a){return '"'+a+'"'})+']')
console.log(strArr)
</script>
</body>
</html>
- 其他阅读:https://segmentfault.com/q/1010000002785082
以上就是关于“js字符串(String)转多维数组(Array) - 代码篇” 的全部内容。