I'm trying to dynamically build a javascript array where _tags is a globally defined array and then send it to php via ajax request. Basically I need the uid as a key and x,y as a sub array. in php it would look something like
$arr[$uid] = array('x'=>$x,'y'=>$y);
but im having trouble figuring out an array like this in javascript, heres what i have
function add_tag_queue(uid,x,y){
var arr = new Array(3);
arr[0] = uid;
arr[1] = x;
arr[2] = y;
_tags.push(arr);
}
This works ok as long as their is only one entry being added to the array, I'm adding multiple values, in other words the function will run a few times and then i want to send that entire array, but this seems to just be adding everything with a comma delimeter.
Im not sure what youre saying exactly here. The second example i previously gave assumes there is a single x,y pair for each uid
but places no limits on how many uid
s are in _tags
. Thats why var _tags = {};
is ourside of the function - so its a global variable.
The following modifications would allow you to have multiple x,y pairs for each uid
:
function add_tag_queue(uid,x,y){
/*
* detect if _tags[uid] already exists with one or more values
* we assume if its not undefined then the value is an array...
* this is similar to doing isset($_tags[$uid]) in php
*/
if(typeof _tags[uid] == 'undefined'){
/*
* use an array literal by enclosing the value in [],
* this makes _tags[uid] and array with eah element of
* that array being a hash with an x and y value
*/
_tags[uid] = [{'x':x,'y':y}];
} else {
// if _tags[uid] is already defined push the new x,y onto it
_tags[uid].push({'x':x, 'y':y});
}
}
This should work:
function add_tag_queue(uid,x,y){
_tags.push([uid, x,y]);
}
if you want the uid
as the key then you need to use an object/hash not an array
var _tags = {}; // tags is an object
function add_tag_queue(uid,x,y){
_tags[uid] = {'x':x,'y':y};
}
You could always just build it in php and json_encode it.
You're looking to implement an associative array in Javascript. While Javascript does not support associative arrays, Javascript objects can be treated much the same.
Try this instead:
_tags = {}
function add_tag_queue(uid,x,y){
_tags[uid] = {x:x, y:y};
}
_tags is now an object and you'll be adding a new object at the uid key. Likewise, the x,y pair is stored in an object. The first x is the key and the second is the value. To clarify, you could write it like this:
function add_tag_queue(uid,xValue,yValue){
_tags[uid] = {x:xValue, y:yValue};
}
It looks very similar to the PHP example you gave:
function add_tag_queue(uid,x,y){
_tags[uid] = {x: x, y: y};
}
This is how I create multidimensional arrays in JS. I hope this helps.
var arr= [];
arr[uid] = new Array();
arr[uid]["x"] = xvalue;
arr[uid]["y"] = yvalue;