Problem printing next 10 numbers in sequence

Asked

Viewed 78 times

0

I’m doing a simple exercise. I need to read a prompt number and print the next 10 on the same line, but the code I created only shows the last one. Someone knows how to solve?

var prompt=require('prompt-sync')()

var numero=Number(prompt('Número: '))

var seguintes= ''
for(var i=1; i<10; i++){
    seguintes=numero+i+', '
}
seguinte=numero+i
console.log(`Seguintes: ${seguintes}`)

I appreciate the answers, both solved this doubt, but I had a bigger doubt, because I have a resolution of this exercise that does not use this accumulator "+=". the following code was tested and actually works but inspired me to create the previous code and left me sincerely confused as to whether or not to use the "+=".

var prompt=require('prompt-sync')()

var num=Number(prompt('Número: '))

var resposta = ''

for(var i=num+1; i<=num+10; i++){
    resposta = resposta + i + ', '
}
console.log(`Seguintes: ${resposta}`)

2 answers

2

The biggest mistake is that it is not accumulating the texts, in each passage it changes the text, even in the last is only what is saved in the variable. The operator = assigned a value to the variable, the += assigns a value to the variable considering the already existing value, so it is an accumulator, which is what you want in all cases.

As can be seen there is no need for parentheses.

I chose to use the literal 10 and not the i. In JS works with var, but does not work with let. And this is considered a language failure to leak the variable into the scope, so I think it’s best to get used to the correct scope always.

I put the ; because although it works in this case you will get used wrong and when you have trouble for the lack of it will be well lost, get used to make an organized code and will program better.

var numero = Number(prompt('Número: '));
var seguintes = '';
for (var i = 1; i < 10; i++) seguintes += numero + i + ', ';
seguintes += numero + 10;
console.log(`Seguintes: ${seguintes}`);

I put in the Github for future reference.

2


The operated + when it is applied to objects Number he adds them up.

When the operator + is applied between Strings and Numbers he converts the Numbers in Strings and concatenates the sentence.

Only separate numerical operations with parentheses ().

var numero = Number(prompt('Número: '))

var seguintes = ''


for (var i = 1; i < 10; i++) {
  seguintes += (numero + i) + ', '
}

seguintes += (numero + i)

console.log(`Seguintes: ${seguintes}`)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.