On Oct 3, 7:09 am, mark4asp <mark4...@gmail.com> wrote:
> How do I use push on to a 2-D array?
var myArray = [];
var myItem = [2, "D"];
myArray.push(myItem);
var myOtherItem = [1, "A"];
myArray.push(myOtherItem);
alert(myArray[0][1]); // "D"
alert(myArray[1][1]); // "A"
Note that I'm using
var myArray = [];
to create an array, in place of
var myArray = new Array();
the two statements are equivalent, though the first is imo more
succinct
>
> Here is my scenario: I have a 2-D array called aSort.
I am unable to make sense of the code you posted. It has a typo.
Remove the typo, it has an infinite loop. etc. You'll get much
better answers if you post code that runs.
> var gridMaxSortCols = 2
This is a number, but you are use a string below as the first
parameter to your push function, "2" != 2
> var aSort = new Array(gridMaxSortCols,2);
Creates a 1-dimensional array: [2, 2] ... I think what you wanted was
var aSort = [ [gridMaxSortCols, 2] ], which creates a 2-dimensional
array with one member -- though your code as written still won't do
what you want
>
> function push(column,order) {
> var aSortTemp = new Array(gridMaxSortCols,2);
creates another array, [2, 2]
> for (var i = 0; i < aSort.length ; i++){
> if (column != gridMaxSortCols[i][0]){
gridMaxSortCols isn't an array, I think you meant if (column !=
aSort[i][0]){
assuming that were fixed, the statement will always evaluate true for
the first item in aSort, as 'column' is a string but aSort[0][0] is a
number
> aSortTemp[i][0] = aSort[i][0];
> aSortTemp[i][1] = aSort[i][1];
> }
> aSort = aSortTemp;
> if(aSort.length == gridMaxSortCols)
> aSort.pop();
>
> aSort.push('2','D'); // what do I do here to push '2','D' ?
Assuming that you meant to call this /outside/ the function
definition, that would result in a 4-member array of two numbers and
two strings: [2, 2, '2', 'D'].
If you want to pass an array as the argument to your function, use
push(['2', 'D']), which passes a single parameter that is an array
with 2 members -- though your code as written still won't do what you
want.
> }
/This/ is where your (infinite) for loop ends.
>
> }
>
> PS: which versions of IE with push() and pop() work with?
I believe 5.5 and up. This page contains an implementation of
Array.push() for IE 5.0.
http://www.robertnyman.com/2005/11/0...tsbyclassname/