开发者

assigning value to array in javascript

in php you could do like this:

 $key1 = 1;
 $key2 = 1;
 $array[$key1][$key2] = 'hi';

in javascript i tried with this:

 key1 = 1;
 key2 = 1;
 var array = new Array();
 array[key1][key2] = 'hi';

but开发者_Go百科 it didnt work. how can i do the same thing in javascript?


Your problem is that you need to instantiate the inner array before assigning values in it

var key1 = 1;
var key2 = 1;
var array = [];
array[key1]=[];
array[key1][key2] = 'hi';

Or you could do it all in one:

var array=[['hi']]

Also, you should avoid assigning to specific indexes unless you're updating an existing element. The first example above will automaticly add an element

array[0]=undefined;

If you want to use specific keys, and not just indexes, you should use dictionaries or objects (dictionaries and objects are the same thing i javascript)


The key1 property of array is undefined at the time you are trying assign the property key2 to it. You need to actually indicate that array[key1] is an array before you start assigning values to it.

For example:

array[key1] = [];
array[key1][key2] = 'hi';


JavaScript is having a problem with the key1 and key2 dimensions of your array being undefined. To correct this problem, these are changes you could make:

var key1 = 1;
var key2 = 1;
// define "array" as an empty array:
var array = [];
// define "array[key1] as an empty array inside that array
// (your second dimension):
array[key1] = [];
array[key1][key2] = 'hi';

PHP does some magic -- you can simply supply 2 keys and PHP "knows what you mean" and will define the $key1 and $key2 dimensions without thinking about it. See: PHP: arrays: If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key.

JavaScript requires you to be more explicit about array creation.


You can find neat implementations. For example, here is a way, which is a function creating an array for the rows and then, creating an array for each column (could be anidated in the other way, but...)

var sDataArray=MultiDimensionalArray(7,2);
//alert(sDataArray[0][0]);
function MultiDimensionalArray(iRows,iCols)
{
var i;
var j;
   var a = new Array(iRows);
   for (i=0; i < iRows; i++)
   {
       a[i] = new Array(iCols);
       for (j=0; j < iCols; j++)
       {
           a[i][j] = "";
       }
   }
   return(a);
} 

The thing is, you just can't work the arrays just like PHP ones. Must treat them the way they really are: an array of arrays (of arrays (of arrays (of arrays)...)). Good luck.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜