如何在JavaScript中将字符串转换为数组?

时间:2011-09-13 17:12:34

标签: javascript arrays string

[["SFO",37.77493,-122.41942],["LAX",34.05223,-118.24368]]

这是我的字符串,我想将其转换为:

arr[0] = ["SFO"....
arr[1] = ["LAX"...

修改

让我澄清一下:

var str = '[["SFO",37.77493,-122.41942],["LAX",34.05223,-118.24368]]'

2 个答案:

答案 0 :(得分:4)

您可以使用JSON.parse

JSON.parse('[["SFO",37.77493,-122.41942],["LAX",34.05223,-118.24368]]')

IE7及以下需要:

<!--[if lt IE 8.]>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<![endif]-->

JSON.parse将字符串转换为javascript对象。数组是对象。上面的字符串将解析成一个数组:

var array = JSON.parse('[["SFO",37.77493,-122.41942],["LAX",34.05223,-118.24368]]')
alert ( typeof array ); // object
alert ( array instanceof Array); // true

答案 1 :(得分:1)

var arr = [["SFO",37.77493,-122.41942],["LAX",34.05223,-118.24368]];
console.log(arr[0]); // ["SFO", 37.77493, -122.41942]
console.log(arr[1]); // ["LAX", 34.05223, -118.24368]