Cycle for javascript

0

Hello I tried to do the following but I do not understand, could someone explain me? please

Create an empty vector. Using a repetitive structure, request the loading of elements by keyboard until zero is entered. Do not store said value in the vector. Then add all the components of the vector, show this sum and the size of the vector.

1) Here is the code, but I do not understand why they do repetitions in indexes ++ and the for, it would not be enough just with the for

2) for example I need to make an array that already has 5 values in which values are entered into the matrix and I have always seen that they compare with array.length, so if I compare it with the array's length would be infinite, assuming that the comparison variable can not be different from 0, then it will always be smaller, what should I do?

var vec=[];
  var valor;
  var indice=0;
  do {
    valor=prompt('Ingrese un valor entero (0 para finalizar)','');
    valor=parseInt(valor);
    if (valor!=0)
    {
      vec[indice]=valor;
      indice++;
    }
  } while (valor!=0);
  var f;
  var suma=0;
  for(f=0;f<vec.length;f++)
  {
    suma=suma+vec[f];
  }
  document.write('Se ingresaron '+vec.length+' valores<br>');
  document.write('La suma de los valores ingresados es:'+suma);

In my second problem I mean to do this:

I have an array with 5 values and I want to enter numbers for keyboards and the common var f = 0 can not be different from 0 which would be like the top to end the for?

    
asked by Eduardo Sebastian 02.05.2017 в 13:11
source

3 answers

2

I respond to each point:

  

but I do not understand why they do repetitions in indices ++ and the for, no   It would be enough with the for.

The first loop while stores each element entered in the matrix vec in the position maintained by the variable indice .

Actually, both the for and the matrix vec are unnecessary. With only the while loop, you could solve the problem by storing the sum and the number of elements in variables:

var suma = 0, valor = 0, numero = 0;
do {
  valor = parseInt(prompt('Ingrese un valor entero (0, ENTER o cualquier otro valor para finalizar)', ''));
  if (isNaN(valor) || valor == 0) {
    break;
  }
  numero++;
  suma += valor;
} while (true);
document.write('<p>Se introdujeron ' + numero + ' valores</p>');
document.write('<p>La suma de los valores ingresados es: ' + suma + '</p>');
  

and my second question is if for example I need to make an array that already   have 5 values in which values are entered into the matrix and   I've always seen that they compare with array.length, so if now what   compared to the length of the array would be infinite, assuming that the   Comparison variable can not be other than 0, then it will be   always smaller, what should I do?

Do not get confused. array.length does not really return the number of elements that currently exist defined in the matrix (different from undefined ), if not the number of elements that would be if all the numerical indexes were used up to the largest one actually used.

You could also have used the variable indice if you feel more comfortable with it and taking into account that it keeps track of the elements you have entered in the matrix.

Another way would have been to use a loop for in or for each in even if it is not an object . Only the defined elements would be selected, without having to traverse them from 0 or going through indices undefined .

Nothing happens if there are previous elements in the matrix, but the initial value of the index should start with the next element and not with 0:

var vec = [2, 5, 7, 9, 12];
var valor;
var indice = vec.length;
do {
  valor = prompt('Ingrese un valor entero (0 para finalizar)','');
  valor = parseInt(valor);
  if (!isNaN(valor) && valor != 0)
  {
    vec[indice++] = valor;
  }
} while (valor != 0);
var f;
var suma=0;
for(f=0; f<vec.length; f++)
{
  suma += vec[f];
}
document.write('Se ingresaron '+vec.length+' valores<br>');
document.write('La suma de los valores ingresados es:'+suma);

Obviously if you use Array.push() you will not need to know the size previous. I would do it (without encapsulating it in an object) thus using Array.forEach :

var vec = [2, 5, 7, 9, 12];
var valor;
do {
  valor = parseInt(prompt('Ingrese un valor entero (0 para finalizar)', ''));
  if (!isNaN(valor) && valor != 0) {
    vec.push(valor);
  }
} while (valor != 0);
var suma = 0;
vec.forEach(function (numero) {
  suma += numero;
});
document.write('<p>Se introdujeron ' + vec.length + ' valores</p>');
document.write('<p>La suma de los valores ingresados es: ' + suma);

A new example for what you propose with indexes out of order:

var vec = [2, 5];
document.write('<p>1.- Aquí la longitud es: ' + vec.length + '</p>');
vec[8] = 1;
document.write('<p>2.- Aquí la longitud es: ' + vec.length + '</p>');
vec[6] = 3;
document.write('<p>3.- Aquí la longitud es: ' + vec.length + '</p>');
var valor;
do {
  valor = parseInt(prompt('Ingrese un valor entero (0 para finalizar)', ''));
  if (!isNaN(valor) && valor != 0) {
    vec.push(valor);
  }
} while (valor != 0);
var suma = 0, num = 0;
vec.forEach(function (numero, indice) {
  suma += numero;
  num++;
  document.write('1.- Elemento ' + indice + ' = ' + numero + '</p>');
});
document.write('<p>Se introdujeron ' + vec.length + ' valores</p>');
document.write('<p>1.- Se introdujeron REALMENTE ' + num + ' valores</p>');
document.write('<p>1.- La suma de los valores ingresados es: ' + suma + '</p>');
suma = 0; num = 0;
for (var indice in vec) {
  suma += vec[indice];
  num ++;
  document.write('2.- Elemento ' + indice + ' = ' + vec[indice] + '</p>');
}
document.write('<p>1.- Se introdujeron REALMENTE ' + num + ' valores</p>');
document.write('<p>2.- La suma de los valores ingresados es: ' + suma + '</p>');

As you can see, in practice a for .. in loop offers results similar to the iteration of Array.forEach .

    
answered by 02.05.2017 / 13:31
source
1
  

I do not understand why they do repetitions in indices ++ and the for, it would not be enough just with the for

Neither do I understand why you use an accountant. It is completely unnecessary , because to add an element to an array you have methods like Array#push , which adds an element in the position following the last current element.

var valor = 0;
var vec = [];
do {
  valor = prompt('Ingrese un valor entero (0 para finalizar)', '');
  valor = parseInt(valor);
  if (valor !== 0) { vec.push(valor); }
} while (valor != 0);

On the need of the for cycle, it is necessary because you are using it to add the values that you have previously stored. The while loop is being used to store values within the array, while for to add those values .

However, it is not necessary to use the for loop to add the array elements. For this you can use the method Array#reduce :

var valor = 0;
var vec = [];
do {
  valor = prompt('Ingrese un valor entero (0 para finalizar)', '');
  valor = parseInt(valor);
  if (valor !== 0) { vec.push(valor); }
} while (valor != 0);

var sum = vec.reduce(function(acc, cur) { return acc + cur; });

console.info('Cantidad de elementos:', vec.length);
console.info('Suma de los elementos:', sum);
  

For example, I need to make an array that already has 5 values in which values are entered into the matrix and I have always seen that they compare with array.length, so if I compare it with the array's length it would be infinite, assuming that the comparison variable can not be different from 0, then it will always be smaller, what should I do?

I do not understand what you mean by this. Whatever you have, you do not need to consider the current size of the array to add new elements.

    
answered by 02.05.2017 в 14:07
0

Here you have it in another way:

var vec = [];
        var valor;
        var suma = 0;
        do {
            valor = parseInt( prompt('Ingrese un valor entero (0 para finalizar)','') );
            if ( valor != 0 ) {
                vec[ vec.length ] = valor;
                suma+= valor;
            }

        } while ( valor != 0 );

        document.write( 'Se ingresaron ' + vec.length + ' valores<br>' );
        document.write( 'La suma de los valores ingresados es:' + suma );
    
answered by 19.05.2018 в 10:39