admin管理员组文章数量:1391947
i have a function
var myarr[] =new Object();
function myfunction(id,msg)
{
myarr[id,msg]
}
I am trying to add msg with id as a key...but its not working...plz help
i have a function
var myarr[] =new Object();
function myfunction(id,msg)
{
myarr[id,msg]
}
I am trying to add msg with id as a key...but its not working...plz help
Share Improve this question asked Nov 4, 2011 at 17:17 abbasabbas 4323 gold badges10 silver badges22 bronze badges 2- 1 var myarr=[]; and myarr[id]=msg; – Birey Commented Nov 4, 2011 at 17:20
- Thanks giys...it worked the braces with my arr was a typo – abbas Commented Nov 4, 2011 at 17:23
5 Answers
Reset to default 7The syntax is:
Declaring myarr:
myarr = {};
Adding an item:
myarr[id] = msg;
JavaScript is not Java.
The following function will create an array consisting of objects.
var myarr = []; //Or: var myarr = {};
function myfunction(id, msg) {
var obj = {}; //Create object
obj[id] = msg; //Set property with key=id, with value=msg
myarr.push(obj); //Use `push` method of the array to insert object in an array
}
If you want to create a single object, and set properies using key=id, and value=msg, use:
var myarr = {};
function myfunction(id, msg){
myarr[id] = msg;
}
I think you mean:
function myfunction(id,msg)
{
myarr[id] = msg;
}
First, you don't included the brackets []
when declaring a variable as an Array or Object in JavaScript.
var myarr = new Object();
Secondly, you need to adjust your assignments:
myarr[id] = msg;
You are misunderstanding how to create associative arrays. Herei s a jsfiddle with the correct functionality.
http://jsfiddle/qRuWz/
本文标签: Javascript associative array problemsStack Overflow
版权声明:本文标题:Javascript associative array problems - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744705693a2620829.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论