2010-12-03 134 views
2

我想动态地建立一个JavaScript数组,其中_tags是一个全局定义的数组,然后通过ajax请求将其发送到php。基本上我需要uid作为键,x,y作为子数组。在PHP它会看起来像我如何动态创建一个多维JavaScript数组

$arr[$uid] = array('x'=>$x,'y'=>$y); 

,但有麻烦的JavaScript找出一个数组这样的IM,继承人我有什么

function add_tag_queue(uid,x,y){ 

    var arr = new Array(3); 
    arr[0] = uid; 
    arr[1] = x; 
    arr[2] = y; 

    _tags.push(arr); 
} 

回答

4

这只要工程确定它们仅仅是 一个条目被添加到数组中, 我添加了多个值,在其他的 单词中该函数将运行几个 时间然后我想发送整个数组的 ,但这似乎只是 将使用逗号 分隔符添加所有内容。

林不知道你在这里说什么。我之前给出的第二个示例假设每个uid都有一个x,y对,但对_tags中有多少个uid没有限制。这就是为什么var _tags = {};是功能的一部分 - 所以它是一个全局变量。

以下修改将允许你有多个X,Y对每个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}); 
    } 
} 

这应该工作:

function add_tag_queue(uid,x,y){ 

    _tags.push([uid, x,y]); 
} 

如果你想uid为重点那么你需要使用一个对象/散列不是array

var _tags = {}; // tags is an object 
function add_tag_queue(uid,x,y){ 

     _tags[uid] = {'x':x,'y':y}; 
    } 
+0

这工作正常,只要他们只有一个条目被添加到数组中,我添加了多个值,换句话说该函数将运行几次,然后我想发送整个数组,但这似乎只是用逗号分隔符添加所有内容。 – Brian 2010-12-03 05:51:11

0

你可以随时在php和json_encode中建立它。

0

您正在寻找在Javascript中实现关联数组。尽管Javascript不支持关联数组,但Javascript对象可以被视为几乎相同。

试试这个:

_tags = {} 

function add_tag_queue(uid,x,y){ 
    _tags[uid] = {x:x, y:y}; 
} 

_tags现在是一个对象,你会在UID键添加一个新的对象。同样,x,y对存储在一个对象中。第一个x是关键字,第二个是值。为了澄清,你可以写这样的:

function add_tag_queue(uid,xValue,yValue){ 
    _tags[uid] = {x:xValue, y:yValue}; 
} 
0

它看起来非常相似,你给PHP的例子:

function add_tag_queue(uid,x,y){ 
    _tags[uid] = {x: x, y: y}; 
} 
0

这是我如何创建JS多维数组。我希望这有帮助。

var arr= []; 
arr[uid] = new Array(); 
arr[uid]["x"] = xvalue; 
arr[uid]["y"] = yvalue;