[英]push values into an array dynamically with javascript
I'm have trouble finding a way to push values into an array dynamically. 我很难找到一种方法将值动态推送到数组中。 I have given the following situation:
我给出了以下情况:
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 fails and says get_anchors[current_anchor] is undefined
Javascript失败,并说
get_anchors[current_anchor] is undefined
How can I make get_anchors[current_anchor]
work. 如何使
get_anchors[current_anchor]
工作。 Or is there a different way to get this done? 或者有不同的方法来完成这项工作?
The desired result should look like 'pitzel','mitzel','sizzle'['sizzle2','sizzle3] 期望的结果应该看起来像'pitzel','mitzel','sizzle'['sizzle2','sizzle3]
Based on your comment it looks like you want a hash map instead of an array. 根据您的评论,您看起来想要一个哈希映射而不是一个数组。 You can use an object for this:
你可以使用一个对象:
var anchors = {
'pitzel': [],
'mitzel': [],
'sizzle': []
};
Then you can do: 然后你可以这样做:
anchors[current_anchor].push('sizzle2', 'sizzle3');
or assuming that anchors
does not have a property with the value of current_anchor
, simply assign a new array: 或者假设
anchors
没有current_anchor
值的属性,只需指定一个新数组:
anchors[current_anchor] = ['fooX', 'fooY'];
Of course you can populate the object dynamically as well. 当然,您也可以动态填充对象。 Have a look at Working with Objects for more information.
有关更多信息,请查看使用对象 。
I'm not sure I understand what you're trying to do, but I think you're trying to insert a few elements after where another occurs. 我不确定我理解你要做什么,但我认为你试图在另一个元素发生之后插入一些元素。 This will do the trick:
这样就可以了:
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' ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.