简体   繁体   中英

How can I convert a string to an Array in JavaScript?

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

That's my string and I want to convert it to:

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

EDIT

Let me clarify:

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

You can use JSON.parse :

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

IE7 and below needs:

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

JSON.parse converts a string into a javascript object. Array's are objects. The string above will parse into an Array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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