简体   繁体   English

JavaScript关联数组问题

[英]Javascript associative array problems

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 我正在尝试添加ID为msg的键作为键...但是它不起作用... PLZ帮助

The syntax is: 语法为:

Declaring myarr: 宣告玛拉:

myarr = {};

Adding an item: 添加项目:

myarr[id] = msg;

JavaScript is not Java. JavaScript不是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: 如果要创建单个对象,并使用key = id和value = msg设置属性,请使用:

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. 首先,在JavaScript中将变量声明为数组或对象时,不要包含方括号[]

var myarr = new Object();

Secondly, you need to adjust your assignments: 其次,您需要调整作业:

myarr[id] = msg;

You are misunderstanding how to create associative arrays. 您误会了如何创建关联数组。 Herei sa jsfiddle with the correct functionality. 在这里,jsfiddle具有正确的功能。

http://jsfiddle.net/qRuWz/ http://jsfiddle.net/qRuWz/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM