使用javascript动态地将值推送到数组中

时间:2012-05-08 13:42:04

标签: javascript arrays array-push

我很难找到一种方法将值动态推送到数组中。我给出了以下情况:

var get_anchors= new Array('pitzel','mitzel','sizzle') 

current_anchor= pics[key].anchor; //has the value 'sizzle'

get_anchors[current_anchor].push(new Array('sizzle2','sizzle3'))

Javascript失败并说get_anchors[current_anchor] is undefined

如何让get_anchors[current_anchor]工作。或者有不同的方法来完成这项工作吗?

期望的结果应该看起来像'pitzel','mitzel','sizzle'['sizzle2','sizzle3]

2 个答案:

答案 0 :(得分:4)

根据您的评论,您似乎需要哈希映射而不是数组。你可以使用一个对象:

var anchors = {
    'pitzel': [],
    'mitzel': [],
    'sizzle': []
};

然后你可以这样做:

anchors[current_anchor].push('sizzle2', 'sizzle3');

或假设anchors没有值为current_anchor的属性,只需指定一个新数组:

anchors[current_anchor] = ['fooX', 'fooY'];

当然,您也可以动态填充对象。有关详细信息,请查看Working with Objects

答案 1 :(得分:0)

我不确定我理解你要做什么,但我认为你试图在另一个元素发生之后插入一些元素。这样就可以了:

var get_anchors = [ 'pitzel', 'mitzel', 'sizzle' ];

current_anchor = get_anchors.indexOf(pics[key].anchor);
get_anchors.splice(current_anchor + 1, 0, 'sizzle2', 'sizzle3');

// get_anchors = [ 'pitzel', 'mitzel', 'sizzle', 'sizzle2', 'sizzle3' ]