I'm trying to put my geolocation coordinates gathered during watchPosition() into an array, so that I can work out total distance later.
I have create a new array
var mapArray;
mapArray = new Array();
then where I assigning my latitude and longitude im putting the values to the array
document.getElementById("currentLat").innerHTML = (position.coords.latitude);
document.getElementById("currentLong").innerHTML = (position.coords.longitude);
document.getElementById("mySpeed").innerHTML = (speedValue.toFixed(1));
mapArray.push(currentLat);
mapArray.push(currentLong);//put values in array
I then want to output them to check it has worked so have tried converting the array to a string
function getArray(){
var outputData = mapArray.toString();
document.getElementById("arrayresult").innerHTML = (outputData);
}
Can anyone see where I'm going wrong at all?
At the moment the output is just 'HTML.SpanElement],[object' over and over again.
thanks.
If you want to use an array, don't use new Array(), use the array literal [] instead, and then we can just assign the whole thing in one go:
var mapArray = [
position.coords.latitude,
position.coords.longitude
];
But, since you already have that convenient position object, why not just rely on that:
function showPosition(position) {
// grab all the keys in position.coords
var keys = Object.keys(position.coords);
// and then map them to "key: value" strings
var pairs = keys.map(function(key) {
return key + ": " + position.coords[key];
});
// join them up with commas between them, and ONLY between them:
var stringified = pairs.join(", ");
// and then set that as our on-page container text
document.getElementById("result").textContent = stringified;
}
And of course we can tighten that since it's fairly straight forward code:
function showPosition(position) {
var result = Object.keys(position.coords).map(function(key) {
return key + ": " + position.coords[key];
}).join(", ");
document.getElementById("result").textContent = result
}
We're also using textContent here, just in case position.coords contains funny keys or values. Setting it as text content, rather than HTML content, means there's no content that can accidentally trigger.
Related
I need to fill an array with each of the values for "name" and "nickname" taken from a SQLITE database and show it in an alert.
This is for a project written in JavaScript in titanium appcelerator.
This is the code:
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
var nickname = fightersRS.fieldByName('nickname');
setFighters.push = {
name: name,
nickname: nickname
};
fightersRS.next();
}
alert(setFighters);
The idea is that the alert displays all comma separated values, for example:
"muhammad ali, rocky balboa, ten shin han, etc ...."
How I can do it? my code does not work.
Change your code as follows
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
var nickname = fightersRS.fieldByName('nickname');
setFighters.push({"name": name, "nickname": nickname}); //This is the correct syntax for pushing an element to the array
fightersRS.next();
}
You can display the elements using a for loop as follows
for(var i=0; i <setFighters.length;i++){
alert("Name = " + setFighters[index].name + " Nickname= " + setFighters[index].nickname);
}
If you want to display their name with comma, try the following
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
setFighters.push(name);
fightersRS.next();
}
var fighters = setFighters.join(",");//Joining the array elements with comma
alert(fighters); //Will display all names with a comma
Look at javascript join method
Use a for loop or inside the while loop only create a string appending all the values with comma.
Fetching all the data from an array with comma is not possible.
Here's an asccociative array example from stack over flow .. you can have your own for loop or use the while loop you are creating
Associative array and fetching data
Thanks
I have this array object that contains arrays:
var webApps = [
['leave empty']
];
I'm ajaxing in some content and the end ajax resulting string will be something like this:
ajaxResult = ',["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]';
My question is, how do I take the returned string and add it to the webApps array?
As #Bergi pointed out, it would probably be a good idea to make your ajax call return valid JSON. If thats not something you have control over, then you need to turn it into valid JSON, parse it, and concat to the webApps array:
var webApps = [
['leave empty']
];
var ajaxResult = ',["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]';
//strip the comma
ajaxResult = ajaxResult.substring(1);
//surround with []
ajaxResult = "[" + ajaxResult + "]";
//parse
ajaxResult = JSON.parse(ajaxResult);
//and concat
webApps = webApps.concat(ajaxResult);
First transform the result into something that is parseable (I hope no other quirks is necessary):
var jsonStr = "["+ajaxResult.slice(1)+"]";
// [["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]]
// would be better if it looked like that in the first place
Now we can parse it, and push the single items on your array:
var arr = JSON.parse(jsonStr);
webApps.push.apply(webApps, arr);
We could've used a loop as well, but push can take multiple arguments so it's easier to apply it.
The following works if the browser supports JSON.
var webApps = [
['leave empty'],['one']
];
var str = JSON.stringify(webApps);
// "[["leave empty"],["one"]]"
str = str.substr(0, str.length-1);
//"[["leave empty"],["one"]"
//var arr = eval(str + ajaxResult + "]");
// more secure way
var arr = JSON.parse(str + ajaxResult + "]");
webApps = eval("[['"+(webApps[0]).toString()+"']"+ajaxResult+"]");
It's weird, but solve your question.
If ajax result is a string, you can convert it to object and add each property to webapps var.
var data = eval('(' + ajaxResult + ')'); // data is a javascript array now, do anything you want
I have 3 fields for user input.. say textbox1,textbox2,textbox3. What i need to do is represent them like this if values are not empty:
Albany, New York, USA
The last textbox value shouldnt have a comma after that. I was able to do it with an associative array but the problem is i couldnt find a way to detect if it was the last value and after that the comma need not appear.Here is what i did
var addressObjToFormat= {};
addressObjToFormat.City = $("#companyentry").find("#City").val();
addressObjToFormat.State = $("#companyentry").find("#State").val();
addressObjToFormat.Country = $("#companyentry").find("#Country").val();
var formattedAddress = $Utils.mapInfoMarkerAddressFormatter(addressObjToFormat);
mapInfoMarkerAddressFormatter = function mapInfoMarkerAddressFormatter(arraddressObjToFormat) {
var formattedAddress = '';
for (var key in addressToFormatObj) {
if (addressToFormatObj.hasOwnProperty(key)) {
if (addressToFormatObj[key] != '') {
formattedAddress += addressToFormatObj[key] + ',';
}
}
}
alert(formattedAddress);
}
Above code gives me result as :
Albany, New York, USA,
Mumbai, Maharshtra, India,
What i want is it should be able to check if its the last field incase if a textbox is left empty and place comma accordingly after each value. Or is there a better way to do this?
You can use substring, jsfiddle
formattedAddress = formattedAddress.substring(0, formattedAddress.length-1);
or
you can save all values in an array and use Array.join eg.
var arr = ['item1','item3','item3','item4'];
formattedAddress = arr.join(' ,');
There are multiple ways to do this
After all your processing, you can just trim off the last ',' as using a regex
formattedAddress = formattedAddress.replace (/,$/g, "");
Alternatively, you can just push your strings into an array and then join them all.
var tmp = [];
for (var key in addressToFormatObj) {
if (addressToFormatObj.hasOwnProperty(key)) {
if (addressToFormatObj[key]) { // your condition
tmp.push(addressToFormatObj[key]);
}
}
}
var formattedAddress = tmp.join(',');
var formattedAddress = addressToFormatObj.join(',');
The array function join() uses its first parameter as a glue to put in between array segments.
I am inserting some data into an array but I am getting
,9,My firstname,My lastname,myemail#example.com,123456789
out in my console. How can I remove comma from first element i.e. 9? here is my code
var data = new Array();
$(row_el.children("td")).each(function(i) {
var td = $(this);
//var data = td.html();
var td_el = td.attr('class');
//arr[i] = data;
if(!td.hasClass("element")) {
data[i] = td.html();
console.log(i + ": " + data);
}
});
I want output like this
9,My firstname,My lastname,myemail#example.com,123456789
then I will pass this array to a function and loop through this array.
Just use push() (MDN docu) instead of setting to a specific position inside your array:
var data = new Array();
$(row_el.children("td")).each(function(i) {
var td = $(this);
//var data = td.html();
var td_el = td.attr('class');
//arr[i] = data;
if(!td.hasClass("element")) {
data.push( td.html() );
console.log(i + ": " + data);
}
});
The problem is, that not all the elements in the array processed by each() result in an entry in your array. However, the index submitted to your callback (i) counts upwards nonetheless. So if there are some elements, that do not result in an entry to your array, these positions are filled with undefined (as long as you enter an element at a later position). These undefined entries now result in an empty string when outputting it the way you do, thus resulting to your leading comma.
I want to get the values of an array that looks like this:
t = new Object();
t.erg = new Array();
t.erg['random1'] = "something1";
t.erg['random2'] = "something2";
t.erg['random3'] = "something3";
t.erg['random4'] = "something4";
But i want to get the random names and then the values of them through a loop, I can't find a way to do it :/
You would use the other form of the for loop:
for (x in t.erg) {
if (t.erg.hasOwnProperty(x)) {
alert("key is " + x + " value is " + t.erg[x]);
}
}
To get a random value, you could get a random number and append it to the end of the string "random".
Something like this might work:
var randomVal = "random" + Math.floor(Math.random()*4);
To get the the names of something you would use a for in loop, but you are actually creating to objects not an object and an array. Why not use literals like this
t={
erg:{
'random1':'something1',
'random2':'something2'
}
}
for(var x in t.erg){
//in the first round of the loop
//x holds random1
}