...

View Full Version : object array and using splits



homeguard
01-06-2012, 10:15 PM
I am trying to parse a string so I can put points into google maps api.

Here is the string i am using:

CountySide Town 66202 KS COUNTRYSIDE,39.025376,-94.766998|Shawnee City 66203 KS SHAWNEE,39.019802,-94.808303


Here is the javascript I am using:


var a = new Array();
function parseAddress(addressString)
{
alert(addressString);
var prompt = addressString.split("|");
for (var i = 0; i < prompt.length; i++) {
var details = prompt[i].split(",");
var t = new Object();
t.name = details[0]
t.lat = details[1]
t.lng = details[2]
a[i] = t;
}
}



I have found if I do something like this:


var t = new Object();
t.name = "Shawnee"
t.lat = 39.019802
t.lng = -94.708303
a[0] = t;

var t = new Object();
t.name = "Overland Park"
t.lat = 38.992488,
t.lng = -94.674769
a[1] = t;

It will work, can someone tell me why my loop doesnt work?

xelawho
01-06-2012, 10:35 PM
you are better using the push function to push objects onto an array:



<html>
<head>
</head>
<body>
<script type="text/javascript">
var a = [];

parseAddress("CountySide Town 66202 KS COUNTRYSIDE,39.025376,-94.766998|Shawnee City 66203 KS SHAWNEE,39.019802,-94.808303")

function parseAddress(addressString){

var deets = addressString.split("|");
for (var i = 0; i < deets.length; i++) {
var details = deets[i].split(",");
var t = new Object();
t.name = details[0]
t.lat = details[1]
t.lng = details[2]
a.push(t);
}
}
</script>

</body>
</html>

Old Pedant
01-07-2012, 12:14 AM
Your loop works just fine. I don't know why you thought it wasn't working.

Complete web page, using your code virtually untouched (I changed it to create the array in the function and then return the array from the function...minor change), and works perfectly.


<html>
<head>
<script type="text/javascript">

function parseAddress(addressString)
{
alert(addressString);
var prompt = addressString.split("|");
var a = new Array();
for (var i = 0; i < prompt.length; i++) {
var details = prompt[i].split(",");
var t = new Object();
t.name = details[0]
t.lat = details[1]
t.lng = details[2]
a[i] = t;
}
return a;
}

var s = "CountySide Town 66202 KS COUNTRYSIDE,39.025376,-94.766998|Shawnee City 66203 KS SHAWNEE,39.019802,-94.808303";

var locations = parseAddress(s);
var show = "";
for ( var n = 0; n < locations.length; ++n )
{
var loc = locations[n];
show += "name: " + loc.name + "\nlat: " + loc.lat + "\nlng: " + loc.lng + "\n--------------\n";
}
alert(show);
</script>
</head>
<body>
</body>
</html>

Old Pedant
01-07-2012, 12:16 AM
AHHH!!! But that was in FireFox!

I'll bet it fails in MSIE! Or maybe Chrome.

And that's because you used the name prompt which is also the function used to prompt users for input!

Try just changing prompt to some other name. Even using Prompt should work, since JS is case sensitive.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum