0

I've a small node.js code that is not working as expected.

There is a for-loop in my code and at the end of for-loop, I'm trying to print the result, but the output that I'm expecting is not matching the output that I'm getting. please let me know on how can I fix it.

Here is my code:

var ttall = "";
var ttall_assists = "";
var total="";
for (var i = 0; i < 3; i++) {
    ttall += 'AAA' + i;
    ttall_assists += 'BBB' + i + '\n';
    total+=`${ttall} ${ttall_assists}`;
}
console.log(`${total}`);

Expected output is:

AAA0 BBB0

AAA1 BBB1

AAA2 BBB2

Currently the output that I get is:

AAA0 BBB0

AAA0AAA1 BBB0

BBB1

AAA0AAA1AAA2 BBB0

BBB1

BBB2

2
  • 1
    Just remove += to be = for variables ttall and ttall_assists . You concatenate strings that's why you got so much data Commented Feb 18, 2019 at 12:15
  • It probably best to just do the following in the loop: console.log(`AAA${i} BBB${i}`);, there is no reason to be creating all those extra variables nor tracking the result in a buffer. All of those extra operations are creating unnecessary overhead.
    – icirellik
    Commented Feb 18, 2019 at 20:43

3 Answers 3

1

You are doing it wrong a little bit.

Using '+=' the next value is added with the previous value. You should use like this

ttall = 'AAA' + i;
ttall_assists = 'BBB' + i + '\n';

Try this and most hopefully you will get the right result

0

you dont need to concatinate the results

var ttall = "";
var ttall_assists = "";
var total="";
for (var i = 0; i < 3; i++) {
    ttall = 'AAA' + i;
    ttall_assists = 'BBB' + i + '\n';
    total+=`${ttall} ${ttall_assists}`;
}
console.log(`${total}`);

0

can you please try like this. I think you will get the expected output

var ttall = "";
var ttall_assists = "";
var total="";
for (var i = 0; i < 3; i++) {
    ttall = 'AAA' + i;
    ttall_assists = 'BBB' + i + '\n';
    total+=`${ttall} ${ttall_assists}`;
}
console.log(`${total}`);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.