2012-07-05 15 views
21

que estoy tratando de empujar a una matriz de dos dimensiones, sin que echar a perder, actualmente mi matriz es:push() una matriz bidimensional

var myArray = [ 
[1,1,1,1,1], 
[1,1,1,1,1], 
[1,1,1,1,1] 
] 

Y mi código que estoy tratando es:

var r = 3; //start from rows 3 
var c = 5; //start from col 5 

var rows = 8; 
var cols = 7; 

for (var i = r; i < rows; i++) 
{ 
    for (var j = c; j < cols; j++) 
    { 
     myArray[i][j].push(0); 
    } 
} 

esto debería resultar en lo siguiente:

var myArray = [ 
[1,1,1,1,1,0,0], 
[1,1,1,1,1,0,0], 
[1,1,1,1,1,0,0], 
[0,0,0,0,0,0,0], 
[0,0,0,0,0,0,0], 
[0,0,0,0,0,0,0], 
] 

pero no y no está seguro si esta es la forma correcta de hacerlo o no.

Entonces, la pregunta es ¿cómo puedo lograr esto?

+2

Lo que * no * ¿es lo que hace? –

Respuesta

30

usted tiene algunos errores en el código:

  1. Uso myArray[i].push(0); para añadir una nueva columna. Su código (myArray[i][j].push(0);) funcionaría en una matriz tridimensional, ya que trata de agregar otro elemento a una matriz en la posición [i][j].
  2. Solo expande (col-d) muchas columnas en todas las filas, incluso en aquellas, que aún no se han inicializado y, por lo tanto, no tienen entradas hasta el momento.

Una correcta, aunque la versión tipo de verbosa, sería el siguiente:

var r = 3; //start from rows 3 
var c = 5; //start from col 5 

var rows = 8; 
var cols = 7; 

// expand to have the correct amount or rows 
for(var i=r; i<rows; i++) { 
    myArray.push([]); 
} 

// expand all rows to have the correct amount of cols 
for (var i = 0; i < rows; i++) 
{ 
    for (var j = myArray[i].length; j < cols; j++) 
    { 
     myArray[i].push(0); 
    } 
} 
+3

Oh, veo cómo funciona ahora, gracias. – Jo3la

2
var r = 3; //start from rows 3 
var c = 5; //start from col 5 

var rows = 8; 

var cols = 7; 


for (var i = 0; i < rows; i++) 

{ 

for (var j = 0; j < cols; j++) 

{ 
    if(j <= c && i <= r) { 
     myArray[i][j] = 1; 
    } else { 
     myArray[i][j] = 0; 
    } 
} 

} 
+2

(1) tiene un error de sintaxis: falta '{' before 'else'. (2) Este código no funcionará, si hay filas para agregar: 'ReferenceError: myArray is not defined'. – Sirko

+1

sí, agregue el {. Hay un error de referencia, porque supongo que esto es una pieza de código en línea y las matrices ya existen como deberían, con respecto al fragmento de arriba. – Daniel

4

Usted tiene que recorrer todas las filas, y añadir las filas y columnas que faltan. Para las filas ya existentes, bucle de C a cols, para las nuevas filas, empuje primero una matriz vacía a la matriz exterior, a continuación, bucle de 0 a cols:

var r = 3; //start from rows 3 
var c = 5; //start from col 5 

var rows = 8; 
var cols = 7; 

for (var i = 0; i < rows; i++) { 
    var start; 
    if (i < r) { 
    start = c; 
    } else { 
    start = 0; 
    myArray.push([]); 
    } 
    for (var j = start; j < cols; j++) { 
     myArray[i].push(0); 
    } 
} 
0

que está llamando el push() en una elemento de la matriz (int), donde push() debe ser llamado en la matriz, también el manejo/llenado de la matriz de esta manera no tiene sentido puede hacerlo de esta manera

for (var i = 0; i < rows - 1; i++) 
{ 
    for (var j = c; j < cols; j++) 
    { 
    myArray[i].push(0); 
    } 
} 


for (var i = r; i < rows - 1; i++) 
{ 

    for (var j = 0; j < cols; j++) 
    { 
     col.push(0); 
    } 
} 

también puede combinar los dos bucles utilizando una condición if, si la fila < r, else if fila> = r

+1

El código que ha dado está equivocado, creo. Por favor marque – 999k

4

Iterar en dos dimensiones significa que deberá verificar dos dimensiones.

suponiendo que esté comenzando con:

var myArray = [ 
    [1,1,1,1,1], 
    [1,1,1,1,1], 
    [1,1,1,1,1] 
]; //don't forget your semi-colons 

desea ampliar esta matriz bidimensional para convertirse en:

var myArray = [ 
    [1,1,1,1,1,0,0], 
    [1,1,1,1,1,0,0], 
    [1,1,1,1,1,0,0], 
    [0,0,0,0,0,0,0], 
    [0,0,0,0,0,0,0], 
    [0,0,0,0,0,0,0], 
]; 

Lo que significa que hay que entender cuál es la diferencia.

de inicio con la matriz externa:

var myArray = [ 
    [...], 
    [...], 
    [...] 
]; 

Si desea realizar esta matriz más tiempo, es necesario comprobar que es la longitud correcta, y añadir más matrices internas para compensar la diferencia:

var i, 
    rows, 
    myArray; 
rows = 8; 
myArray = [...]; //see first example above 
for (i = 0; i < rows; i += 1) { 
    //check if the index exists in the outer array 
    if (!(i in myArray)) { 
     //if it doesn't exist, we need another array to fill 
     myArray.push([]); 
    } 
} 

el siguiente paso requiere iterar sobre todas las columnas de cada matriz, vamos a construir en el código original:

var i, 
    j, 
    row, 
    rows, 
    cols, 
    myArray; 
rows = 8; 
cols = 7; //adding columns in this time 
myArray = [...]; //see first example above 
for (i = 0; i < rows; i += 1) { 
    //check if the index exists in the outer array (row) 
    if (!(i in myArray)) { 
     //if it doesn't exist, we need another array to fill 
     myArray[i] = []; 
    } 
    row = myArray[i]; 
    for (j = 0; j < cols; j += 1) { 
     //check if the index exists in the inner array (column) 
     if (!(i in row)) { 
      //if it doesn't exist, we need to fill it with `0` 
      row[j] = 0; 
     } 
    } 
} 
3

En su caso se puede hacer eso sin usar push en absoluto:

var myArray = [ 
    [1,1,1,1,1], 
    [1,1,1,1,1], 
    [1,1,1,1,1] 
] 

var newRows = 8; 
var newCols = 7; 

var item; 

for (var i = 0; i < newRows; i++) { 
    item = myArray[i] || (myArray[i] = []); 

    for (var k = item.length; k < newCols; k++) 
     item[k] = 0;  
} 
+1

Gracias muy útil, ¿es posible eliminar las filas agregadas? Tal vez pueda usar el mismo método anterior pero en su lugar empalme el elemento [k] .splice (k, 1) para eliminar las filas/cols agregadas – Jo3la

+1

Como la fila agregada se anexa, puede usar 'length' para eliminarlas:' myArray .length = 3'; hace que los últimos '5' sean descartados (se supone que tienes' 8' filas). – ZER0

+1

Ah ha no pensó que fuera posible con la .length, ahora funciona ... gracias. – Jo3la

0

Crear am matriz y poner dentro de la primera, en este caso puedo recuperar los datos de respuesta JSON

$.getJSON('/Tool/GetAllActiviesStatus/', 
    var dataFC = new Array(); 
    function (data) { 
     for (var i = 0; i < data.Result.length; i++) { 
      var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true); 
      dataFC.push(serie); 
     }); 
Cuestiones relacionadas