我如何动态创建多维javascript数组
我正在尝试动态构建一个javascript数组,其中_tags是一个全局定义的数组,然后通过ajax请求将其发送到php。基本上我需要 uid 作为键,x,y 作为子数组。在 php 中,它看起来像这样
$arr[$uid] = array('x'=>$x,'y'=>$y);
,但我在 javascript 中无法找出这样的数组,这就是我所拥有的
function add_tag_queue(uid,x,y){
var arr = new Array(3);
arr[0] = uid;
arr[1] = x;
arr[2] = y;
_tags.push(arr);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不确定你在这里到底在说什么。我之前给出的第二个示例假设每个
uid
都有一个 x,y 对,但对_tags
中有多少个uid
没有限制>。这就是为什么var _tags = {};
位于函数的我们这边 - 所以它是一个全局变量。以下修改将允许您为每个
uid
拥有多个 x,y 对:这应该可行:
如果您希望将
uid
作为键,那么您需要使用一个对象/hash 不是数组
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 manyuid
s are in_tags
. Thats whyvar _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
:This should work:
if you want the
uid
as the key then you need to use an object/hash not anarray
你总是可以用 php 构建它并对其进行 json_encode 。
You could always just build it in php and json_encode it.
您正在寻找在 Javascript 中实现关联数组。虽然 Javascript 不支持关联数组,但 Javascript 对象的处理方式大致相同。
请尝试这样做:
_tags 现在是一个对象,您将在 uid 键处添加一个新对象。同样,x,y 对存储在一个对象中。第一个 x 是键,第二个 x 是值。为了澄清,你可以这样写:
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 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:
它看起来与您给出的 PHP 示例非常相似:
It looks very similar to the PHP example you gave:
这就是我在 JS 中创建多维数组的方法。我希望这有帮助。
This is how I create multidimensional arrays in JS. I hope this helps.