Foros del Web » Programando para Internet » Javascript »

arrays

Estas en el tema de arrays en el foro de Javascript en Foros del Web. Muy buenas tarde. Hago este tema para saber porque no me funciona el siguiente código: var cArray = new Array(7); var pArray = new Array(7); ...
  #1 (permalink)  
Antiguo 14/10/2012, 11:41
 
Fecha de Ingreso: abril-2012
Ubicación: Malaga
Mensajes: 46
Antigüedad: 12 años
Puntos: 0
arrays

Muy buenas tarde.
Hago este tema para saber porque no me funciona el siguiente código:

var cArray = new Array(7);
var pArray = new Array(7);
var nArray = new Array(7);
var tArray = new Array(7);
var totalcompra = 0;

cArray[0] = document.getElementById('c').value;
cArray[1] = document.getElementById('c1').value;
cArray[2] = document.getElementById('c2').value;
cArray[3] = document.getElementById('c3').value;
cArray[4] = document.getElementById('c4').value;
cArray[5] = document.getElementById('c5').value;

pArray[0] = document.getElementById('a').value;
pArray[1] = document.getElementById('a1').value;
pArray[2] = document.getElementById('a2').value;
pArray[3] = document.getElementById('a3').value;
pArray[4] = document.getElementById('a4').value;
pArray[5] = document.getElementById('a5').value;

for (var i = 0; i <= 7; i++)
{
totalcompra = totalcompra + (parseInt(cArray[i]) + parseInt(pArray[i])) ;


}

alert(totalcompra);

A la hora de ejecutar me sale que totalcompra es NaN.
Nose donde fallo, si alguien sabe donde esta el error decidmelo por favor.

Gracias
  #2 (permalink)  
Antiguo 14/10/2012, 13:43
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: arrays

Por que 7? si tu array no tiene esa cantidad de elementos
Supongo, sin ver tu html, que sería algo asi

Código HTML:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <title>titulo</title>
  5. <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  6.  
  7. <script type="text/javascript">
  8. //<![CDATA[
  9. function suma(){
  10. var cArray = new Array();
  11. var pArray = new Array();
  12. var nArray = new Array();
  13. var tArray = new Array();
  14. var totalcompra = 0;
  15.  
  16. cArray[0] = document.getElementById('c').value;
  17. cArray[1] = document.getElementById('c1').value;
  18. cArray[2] = document.getElementById('c2').value;
  19. cArray[3] = document.getElementById('c3').value;
  20. cArray[4] = document.getElementById('c4').value;
  21. cArray[5] = document.getElementById('c5').value;
  22.  
  23. pArray[0] = document.getElementById('a').value;
  24. pArray[1] = document.getElementById('a1').value;
  25. pArray[2] = document.getElementById('a2').value;
  26. pArray[3] = document.getElementById('a3').value;
  27. pArray[4] = document.getElementById('a4').value;
  28. pArray[5] = document.getElementById('a5').value;
  29.  
  30. for (i=0;i<cArray.length;i++)
  31.  
  32. {
  33. totalcompra = totalcompra + (parseInt(cArray[i]) + parseInt(pArray[i])) ;
  34. //alert(parseInt(cArray[i]) + parseInt(pArray[i]));
  35.  
  36. }
  37.  
  38. alert(totalcompra);
  39. }
  40. //]]>
  41. </head>
  42. <body onload="suma();">
  43. <form action="#">
  44. <p>
  45. <input type="text" id="a" value="5" />
  46. <input type="text" id="a1" value="5" />
  47. <input type="text" id="a2" value="5" />
  48. <input type="text" id="a3" value="5" />
  49. <input type="text" id="a4" value="5" />
  50. <input type="text" id="a5" value="5" />
  51. <br />
  52. <input type="text" id="c" value="8" />
  53. <input type="text" id="c1" value="5" />
  54. <input type="text" id="c2" value="5" />
  55. <input type="text" id="c3" value="5" />
  56. <input type="text" id="c4" value="5" />
  57. <input type="text" id="c5" value="5" />
  58. </p>
  59. </form>
  60. </body>
  61. </html>

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #3 (permalink)  
Antiguo 14/10/2012, 13:56
 
Fecha de Ingreso: abril-2012
Ubicación: Malaga
Mensajes: 46
Antigüedad: 12 años
Puntos: 0
Respuesta: arrays

Este es el código que tengo ( ya he quitado el tamaño del array)
Código HTML:
Ver original
  1.     <head>
  2.         <title>Factura</title>
  3.         <script>
  4.             function precio_total ()
  5.             {
  6.                 var cArray = new Array ();
  7.                 var pArray = new Array ();
  8.                 var nArray = new Array ();
  9.                 var tArray = new Array ();
  10.                 var totalcompra = 0;
  11.                
  12.                 cArray[0] = document.getElementById('c').value;
  13.                 cArray[1] = document.getElementById('c1').value;
  14.                 cArray[2] = document.getElementById('c2').value;
  15.                 cArray[3] = document.getElementById('c3').value;
  16.                 cArray[4] = document.getElementById('c4').value;
  17.                 cArray[5] = document.getElementById('c5').value;
  18.                 cArray[6] = document.getElementById('c6').value;
  19.                
  20.                 pArray[0] = document.getElementById('a').value;
  21.                 pArray[1] = document.getElementById('a1').value;
  22.                 pArray[2] = document.getElementById('a2').value;
  23.                 pArray[3] = document.getElementById('a3').value;
  24.                 pArray[4] = document.getElementById('a4').value;
  25.                 pArray[5] = document.getElementById('a5').value;
  26.                 pArray[6] = document.getElementById('a6').value;
  27.                
  28.                 for (var i = 0; i <= 6; i++)
  29.                 {  
  30.                     totalcompra = totalcompra + (parseInt(cArray[i]) * parseInt(pArray[i])) ;
  31.                    
  32.                
  33.                 }
  34.                
  35.                 alert(totalcompra);
  36.                
  37.             }
  38.  
  39.         </script>
  40.     </head>
  41.     <body>
  42.         <form>
  43.             <table border="1">
  44.                 <tr>
  45.                     <td >Nombre Art&iacute;culo</td>
  46.                     <td >Cantidad</td>
  47.                     <td >Precio(articulo)</td>
  48.                 </tr>
  49.                 <tr>
  50.                     <td ><input type="text" id="n"></td>
  51.                     <td ><input type="text" id="c"></td>
  52.                     <td ><input type="text" id="a"></td>   
  53.                 </tr>
  54.                 <tr>
  55.                     <td ><input type="text" id="n1"></td>
  56.                     <td ><input type="text" id="c1"></td>
  57.                     <td ><input type="text" id="a1"></td>
  58.                    
  59.                 </tr>
  60.                 <tr>
  61.                     <td ><input type="text" id="n2"></td>
  62.                     <td ><input type="text" id="c2"></td>
  63.                     <td ><input type="text" id="a2"></td>
  64.                    
  65.                 </tr>
  66.                 <tr>
  67.                     <td ><input type="text" id="n3"></td>
  68.                     <td ><input type="text" id="c3"></td>
  69.                     <td ><input type="text" id="a3"></td>
  70.                    
  71.                 </tr>
  72.                 <tr>
  73.                     <td ><input type="text" id="n4"></td>
  74.                     <td ><input type="text" id="c4"></td>
  75.                     <td ><input type="text" id="a4"></td>
  76.                    
  77.                 </tr>
  78.                 <tr>
  79.                     <td ><input type="text" id="n5"></td>
  80.                     <td ><input type="text" id="c5"></td>
  81.                     <td ><input type="text" id="a5"></td>
  82.                    
  83.                 </tr>
  84.                 <tr>
  85.                     <td ><input type="text" id="n6"></td>
  86.                     <td ><input type="text" id="c6"></td>
  87.                     <td ><input type="text" id="a6"></td>
  88.                    
  89.                 </tr>
  90.                 <tr>
  91.                     <td ><input type="text" id="n7"></td>
  92.                     <td ><input type="text" id="c7"></td>
  93.                     <td ><input type="text" id="a7"></td>
  94.                    
  95.                 </tr>
  96.                 <tr>
  97.                     <td colspan="4" align="right"><input type="button" style="width:100px" id="boton" value="total" onClick= "precio_total ()"></td>
  98.                 </tr>
  99.                
  100.             </table>
  101.         </form>
  102.     </body>
  103. </html>

Lo que pasa es que si pongo "totalcompra = totalcompra + (parseInt(cArray[0]) * parseInt(pArray[0])) ;" si me sale la multiplicación entre ambos, pero al poner "i" me sale NaN, y no se dónde está el fallo
  #4 (permalink)  
Antiguo 14/10/2012, 14:42
(Desactivado)
 
Fecha de Ingreso: noviembre-2002
Ubicación: Ciudad Autónoma de Buenos Aires
Mensajes: 2.367
Antigüedad: 21 años, 5 meses
Puntos: 317
Respuesta: arrays

Es que ya te lo resolvieron.

¿Entendés el código?

Suponiendo que la respuesta sea "sí", ¿miraste la corrección?

Probé el tuyo con los valores 0 por omisión en todos los input y funciona perfectamente. Puede que alguna sintaxis no sea reconocida en algún navegador, pero en principio, anda.
  #5 (permalink)  
Antiguo 14/10/2012, 15:20
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: arrays

Cuando hacés cosas como estas, lo primero es validar que los campos NO estén vacíos y que contengan, obviamente, un número

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #6 (permalink)  
Antiguo 15/10/2012, 06:46
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: arrays

Cita:
var arr = (cArray[i] == '')? 0:parseInt(cArray[i]);
totalcompra += (arr * pArray[i]);
se valida que el control cantidad no esté vacío. en caso de estar vacío, su valor será 0. el control precio ha de tener un valor por defecto
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #7 (permalink)  
Antiguo 16/10/2012, 08:00
 
Fecha de Ingreso: abril-2012
Ubicación: Malaga
Mensajes: 46
Antigüedad: 12 años
Puntos: 0
Respuesta: arrays

Ya lo hice, pero de otra forma xD
Gracias por las respuestas

Por cierto, ¿cómo hago que, si una posición del array que está vacío me ponga un 0 en vez de "undefined"?

Ésta es la función que tengo, a ver si me podéis decir donde fallo xD:
Código HTML:
Ver original
  1. function precio_total ()
  2.             {
  3.                 var cArray = new Array ();
  4.                 var pArray = new Array ();
  5.                 var nArray = new Array ();
  6.                 var tArray = new Array ();
  7.                 var totalcompra = 0;
  8.                
  9.                 cArray[0] = document.getElementById('c').value;
  10.                 cArray[1] = document.getElementById('c1').value;
  11.                 cArray[2] = document.getElementById('c2').value;
  12.                 cArray[3] = document.getElementById('c3').value;
  13.                 cArray[4] = document.getElementById('c4').value;
  14.                 cArray[5] = document.getElementById('c5').value;
  15.                 cArray[6] = document.getElementById('c6').value;
  16.                 cArray[7] = document.getElementById('c7').value;
  17.                
  18.                 pArray[0] = document.getElementById('a').value;
  19.                 pArray[1] = document.getElementById('a1').value;
  20.                 pArray[2] = document.getElementById('a2').value;
  21.                 pArray[3] = document.getElementById('a3').value;
  22.                 pArray[4] = document.getElementById('a4').value;
  23.                 pArray[5] = document.getElementById('a5').value;
  24.                 pArray[6] = document.getElementById('a6').value;
  25.                 pArray[7] = document.getElementById('a7').value;
  26.                
  27.                 for (var i = 0; i <= 6; i++)
  28.                 {  
  29.                     if (cArray[i] == "")
  30.                     {
  31.                         totalcompra=totalcompra;
  32.                     }
  33.                     else
  34.                     {
  35.                         if(pArray[i] == "")
  36.                         {
  37.                             totalcompra=totalcompra;
  38.                         }
  39.                         else
  40.                         {
  41.                             totalcompra = totalcompra + (parseInt(cArray[i]) * parseInt(pArray[i])) ;
  42.                             tArray[i] = parseInt(cArray[i]) * parseInt(pArray[i]);
  43.                         }
  44.                     }
  45.                    
  46.                     if(tArray[i] == "")
  47.                     {
  48.                         tArray[i] = 0;
  49.                     }
  50.                
  51.                 }
  52.                
  53.                 /*for (var x=0; x <=6; x++)
  54.                 {
  55.                     if(tArray[x] == "")
  56.                     {
  57.                         tArray[x] = 27;
  58.                     }
  59.                 }*/

Saludos y gracias de nuevo
  #8 (permalink)  
Antiguo 16/10/2012, 08:51
(Desactivado)
 
Fecha de Ingreso: noviembre-2002
Ubicación: Ciudad Autónoma de Buenos Aires
Mensajes: 2.367
Antigüedad: 21 años, 5 meses
Puntos: 317
Respuesta: arrays

Lo validás igual que hacés cuando buscás uno vacío (""), pero con undefined.

Una duda ¿los valores en dinero son siempre redondos? ¿No hay centavos?.
  #9 (permalink)  
Antiguo 16/10/2012, 15:04
 
Fecha de Ingreso: abril-2012
Ubicación: Malaga
Mensajes: 46
Antigüedad: 12 años
Puntos: 0
Respuesta: arrays

Ya está.
La verdad es que lo de los céntimos no me lo pedía, pero me gustaría saber como se haría, por si en algún momento me lo piden.

Gracias por su ayuda
  #10 (permalink)  
Antiguo 16/10/2012, 18:29
(Desactivado)
 
Fecha de Ingreso: noviembre-2002
Ubicación: Ciudad Autónoma de Buenos Aires
Mensajes: 2.367
Antigüedad: 21 años, 5 meses
Puntos: 317
Respuesta: arrays

Decinos la verdad : en tu vida abriste un manual de javascript, ¿no?.

Y lo peor es que no te puedo decir nada, porque apenas te explicamos cómo se mira un asunto, lo resolvés.
Supongo que ya tenés experiencia con otros lenguajes.

Para los decimales, validás con parseFloat().
parseInt() te devuelve solamente la parte entera.

Igual, me parece que habría que poner una máscara, para que siempre el valor termine con céntimos, aunque sean 0.00. Pero sería una exquisitez. Esperá a que te lo pidan y después te ocupás.

Etiquetas: arrays, funcion
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:14.