最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to append new elements to the same key in a hash - Stack Overflow

matteradmin6PV0评论

I am kind of very new to javascript world. I have a doubt. How do i add/append new values to existing hash. example

var setname = 'set_1', elements = {};
elements[setname] = ['beer','water','wine'];
alert(elements['set_1']);

Now how do i dynamically add more elements to set_1 key? like to extend the set_1 with coffee tea.

Sorry if this question has been repeated and is very trivial, i did my search. I found one article realted to it,how to assign variable value as variable name in a hash?

I am kind of very new to javascript world. I have a doubt. How do i add/append new values to existing hash. example

var setname = 'set_1', elements = {};
elements[setname] = ['beer','water','wine'];
alert(elements['set_1']);

Now how do i dynamically add more elements to set_1 key? like to extend the set_1 with coffee tea.

Sorry if this question has been repeated and is very trivial, i did my search. I found one article realted to it,how to assign variable value as variable name in a hash?

Share Improve this question edited May 23, 2017 at 11:55 CommunityBot 11 silver badge asked Jan 9, 2012 at 18:43 SaiSai 1132 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Here, elements['set_1'] is just a normal Javascript array. The fact that it is a property of the elements object is pletely immaterial to how it behaves. You can add items to it in the normal Javascript way: with push:

elements['set_1'].push('coffee');
elements['set_1'].push('tea');

If you don't know what the property's name will be when you write your code, you can do exactly the same with a variable:

elements[setname].push('coffee');
elements[setname].push('tea');
elements['set_1'].push('foo');

If the value of set_1 is an array you can do this:

var setname = 'set_1', elements = {};
elements[setname] = ['beer','water','wine'];
elements[setname].push('new item');
alert(elements['set_1']);

However, if it is not an array, you will need to take different action.

Post a comment

comment list (0)

  1. No comments so far